题目链接:LeetCode40
欢迎留言交流,每天都会回消息。
class Solution {List<List<Integer>> rs = new ArrayList<>();LinkedList<Integer> path = new LinkedList<>();public List<List<Integer>> combinationSum2(int[] candidates, int target) {Arrays.sort(candidates);backTracking(candidates, target, 0, 0);return rs;}void backTracking(int[] candidates, int target, int sum, int startIdx) {if (sum > target) {return;}if (sum == target) {rs.add(new ArrayList<Integer>(path));return;}for (int i = startIdx; i < candidates.length; i++) {if (i > startIdx && candidates[i] == candidates[i - 1]) {continue;}sum += candidates[i];path.add(candidates[i]);backTracking(candidates, target, sum, i + 1);path.removeLast();sum -= candidates[i];}}
}