【Leetcode】Combination Sum (Backtracking)

来源:互联网 发布:乎的组词 编辑:程序博客网 时间:2024/05/23 17:37

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

代码参考Ganker_Code

public static ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();ArrayList<Integer> temp = new ArrayList<Integer>();if (candidates == null || candidates.length == 0)return result;Arrays.sort(candidates);helper(candidates, 0, target, temp, result);return result;}public static void helper(int[] candidates, int start, int target,ArrayList<Integer> temp, ArrayList<ArrayList<Integer>> result) {if (target == 0) {result.add(new ArrayList<Integer>(temp));return;}if (target < 0)return;for (int i = start; i < candidates.length; i++) {if (i > start && candidates[i] == candidates[i - 1])continue;temp.add(candidates[i]);helper(candidates, i, target - candidates[i], temp, result);temp.remove(temp.size() - 1);}}

至于为什么要在for加上if判断,因为在选元素的时候,假定数组里面的元素是没有重复了,所以有了重复就要跳过

比如数组[2,3] 目标7的情况得到的结果是[2,2,3]

但是如果是[2,2,3] 目标7的情况就会得到[2,2,3][2,2,3][2,2,3]

就会多出重复的两个数组。

还有就是“i>start”比“i>0”更好,

因为当第一次“i==start”的时候,代表这个数没有被用过,如果i>0就是让我们放弃这个数,但是candidates[i]==candidates[i-1]这个条件不答应,因为当i==start的时候,一定是candidates[i]!=candidates[i-1]的时候,这样i才有机会进helper方法的递归体。这样需要判断两次,

如果是i>start,那么就说明这个数必须被用过才能被抛弃,所以当i==start的时候,i>start肯定不会答应的。只需要判断一次就可以,就可以省过后面的candidates[i]==candidates[i-1]判断。



0 0
原创粉丝点击