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]
]

思路:
Subsets全部子集:可以重复1,2,2。但是同一个元素只能用一次 //内部乱排无所谓

Permutations II 全排列可重复版本:必须重复1,2,2。但是同一个元素只能用一次。//内部不能乱排,所以要再加一个used[i]的数组

Combination Sum选元素求和,顺序无关:也是一样//内部乱排无所谓

 

重复的压根不能用:

if (i > start && nums[i] == nums[i - 1]) //重复的压根不能用
                    continue;

 


class Solution {
    public List<List<Integer>> combinationSum2(int[] nums, int target) {
        //cc
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        if (nums == null || nums.length == 0)
            return results;
        
        //排序一下
        Arrays.sort(nums);
        
        backtrace(nums, new ArrayList<Integer>(), 0, 0,
                         target, results);
        
        return results;
    }
    
    public void backtrace(int[] nums, List<Integer> temp, int start, 
                          int currentSum,
                          int target, List<List<Integer>> results) {
        //exit
        if (currentSum == target) {
            results.add(new ArrayList<>(temp)); //必须这样写
        }else if (currentSum > target) {
            return ;
        }else {
            for (int i = start; i < nums.length; i++) {
                if (i > start && nums[i] == nums[i - 1]) //重复的压根不能用
                    continue;
            
                temp.add(nums[i]);
                backtrace(nums, temp, i, currentSum + nums[i],
                         target, results);
                temp.remove(temp.size() - 1);
            }
        }
    }
}
View Code

 



posted @ 2020-08-13 23:17  苗妙苗  阅读(149)  评论(0编辑  收藏  举报