Combination Sum II —— LeetCode

3290 ワード

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 (a1, a2, … , 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]
    前の問題と似ていますが、候補セットの要素は一度しか現れません.
    問題解決の考え方:現在の要素の次からsumを計算し、candidateをリストに追加し、重複要素をスキップします.
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    
            List<List<Integer>> res = new ArrayList<>();
    
            if (candidates == null || candidates.length == 0) {
    
                return res;
    
            }
    
            Deque<Integer> tmp = new ArrayDeque<>();
    
            Arrays.sort(candidates);
    
            helper(res, tmp, 0, target, candidates);
    
            return res;
    
        }
    
    
    
        private void helper(List<List<Integer>> res, Deque<Integer> tmp, int start, int target, int[] candidate) {
    
            if (target == 0) {
    
                res.add(new ArrayList<>(tmp));
    
    //            System.out.println(tmp);
    
                return;
    
            }
    
            for (int i = start; i < candidate.length && target >= candidate[i]; i++) {
    
                tmp.addLast(candidate[i]);
    
                helper(res, tmp, i + 1, target - candidate[i], candidate);
    
                tmp.removeLast();
    
                while (i < candidate.length - 1 && candidate[i + 1] == candidate[i]) {
    
                    i++;
    
                }
    
            }
    
        }