LeetCode 40. Combination Sum II

LeetCode 40. Combination Sum II

    • Description
    • Note
    • Example
    • Code
    • Conclusion

Description

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

LeetCode 40. Combination Sum II_第1张图片

Code

  • java
class Solution {
    private List<List<Integer>> result;
    
    public void dfs(int[] candidates, int index, LinkedList list, int sum, int target) {
        if(sum == target) {
            result.add(new LinkedList<Integer>(list));
            return;
        }
        for(int i = index; i < candidates.length; i++) {
            if(i > index && candidates[i] == candidates[i-1]) continue;
            if(sum + candidates[i] <= target) {
                list.add(candidates[i]);
                dfs(candidates, i+1, list, sum+candidates[i], target);
                list.removeLast();
            }
        }
    }
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        LinkedList list = new LinkedList<Integer>();
        result = new LinkedList<List<Integer>>();
        Arrays.sort(candidates);
        dfs(candidates, 0, list, 0, target);
        return result;
    }
}

Conclusion

  • 上题的变型
  • 需要排序,有重复的数
  • 学习大佬的物理去重方法

你可能感兴趣的:(LeetCode,LeetCode)