leetcode40:Combination Sum II

思路:本题在于数字不能重复使用,而且需要去重,可以先将数组排序,然后去重就方便了,依然采用深度优先的方法。

代码:

public class CombinationSumII {

	public static void main(String[] args) {
		int[] num = { 2, 5, 2, 1, 2 };

		System.out.println(combinationSum(num, 5));
	}

	public static List<List<Integer>> combinationSum(int[] candidates, int target) {
		List<List<Integer>> ls = new ArrayList<>();
		List<Integer> list = new ArrayList<>();
		Arrays.sort(candidates);
		helpCombinationSum(candidates, target, 0, ls, list);
		return ls;
	}

	private static void helpCombinationSum(int[] num, int target, int index, List<List<Integer>> ls,
			List<Integer> list) {
		if (target == 0 && !ls.contains(list))// 此处注意contains和containsAll的区别
			ls.add(new ArrayList(list));
		if (index >= num.length || target < 0)//注意此处等号,如果放在上面,需要去掉等号
			return;
		for (int i = index; i < num.length; i++) {
			list.add(num[i]);
			helpCombinationSum(num, target - num[i], i + 1, ls, list);
			list.remove(list.size() - 1);
		}

	}
}

输出:

leetcode40:Combination Sum II

 

相关文章: