【leetcode】40. Combination Sum II

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

Each number in candidates may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]

題解如下:

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> tmp = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(res,tmp,candidates,target,0);
        return res;
    }
    
    public void backtrack(List<List<Integer>> res,List<Integer> tmp,
                         int[] candidates,int target,int idx) {
        if(target == 0) {
            res.add(new ArrayList(tmp));
            return;
        }
        for(int i = idx;i < candidates.length;i++) {
            if(i > idx && candidates[i] == candidates[i- 1])
                continue;
            if(target >= candidates[i]) {
                target -= candidates[i];
                tmp.add(candidates[i]);
                backtrack(res,tmp,candidates,target,i+1);
                tmp.remove(tmp.size()-1);
                target += candidates[i];
            }
        }
    }
}

 

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