leetcode刷题之旅(40)组合总和2

题目描述

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。 

 

样例

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]

思路分析

思路和上题一致,不过数组中出现了重复元素,所以要加判断条件,防止list中出现重复项

 

代码及结果

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
		List<List<Integer>> list = new ArrayList<List<Integer>>();
		List<Integer> list1 = new ArrayList<Integer>();
		Arrays.sort(candidates);
		dfs(candidates, 0, target, list, list1);
		return list;
	}
	void dfs(int[] candidates, int start, int target, List<List<Integer>> list, List<Integer> list1){
		if (target < 0) {
			return;
		}
		else if (target == 0) {
			list.add(new ArrayList<Integer>(list1));
		}
		else {
			for (int i = start; i < candidates.length; i++) {
				if (i>start && candidates[i]==candidates[i-1]) {  //判断条件
					continue;
				}
				list1.add(candidates[i]);
				dfs(candidates, i+1, target-candidates[i], list, list1);  //改为i+1 避免元素多次使用
				list1.remove(list1.size() - 1);
			}
		}
	}

leetcode刷题之旅(40)组合总和2