[LeetCode] Combination Sum II

Total Accepted: 7633 Total Submissions: 31949

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] 

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum2(int[] num, int target) {
        ArrayList<ArrayList<Integer>>   list = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer>              path = new ArrayList<Integer>();
        
        Arrays.sort(num);
        
        dfs(num, list, path, 0, target);
        
        return list;
    }
    
    public void dfs(int[] num, ArrayList<ArrayList<Integer>> list, 
        ArrayList<Integer> path, int index, int target) {
        if (target == 0) {
            list.add(new ArrayList<Integer>(path));
            return;
        }
        
        for (int i = index; i < num.length; i++) {
            if (num[i] > target) break;
            
            path.add(num[i]);
            dfs(num, list, path, i + 1, target - num[i]);
            path.remove(path.size() - 1);
            // skip repeated numbers
            while (i < num.length - 1 && num[i+1] == num[i]) i++;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章