2015年4月3日星期五

Combination Sum II leetcode

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6] 

这道题首先考虑
1.什么时候跳出 target <0 和 target=0两种情况
2. 递归传入什么参数? 因为重复组不算 每次从i+1传入
3. 避免重复:i != pos时候 如果num[i]&num[i-1]相等,说明num[i-1]已经取过应该跳过num[i]    1,2(1)] 那么[1,2(2)]就是重复选取 为了确保这种情况不发生,



  public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> tem = new ArrayList<Integer>();
        if (num == null){
            return result;
        }
        Arrays.sort(num);
        dfs(result, tem, num, target, 0);
        return result;
    }
    public void dfs(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> tem, int[] num, int target, int pos){
        if (target < 0){
            return;
        }
        if (target == 0){
            result.add(new ArrayList<Integer>(tem));
            return;
        }
        for (int i = pos; i < num.length; i++){
            if (i != pos && num[i] == num[i - 1]){
                continue;
            }
            tem.add(num[i]);
            dfs(result, tem, num, target - num[i], i + 1);
            tem.remove(tem.size() - 1);
        }
    }
}

没有评论:

发表评论