zoukankan      html  css  js  c++  java
  • 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
    
    
    


  • 相关阅读:
    Qt 6 正式发布
    GTK 4.0 正式发布
    编译 flink 1.12.0
    Flink 1.12.0 sql 任务指定 job name
    【翻译】Apache Flink 1.12.0 Release Announcement
    【源码】Flink 三层图结构 —— JobGraph 生成过程
    【源码】Flink 算子 chain 在一起的条件
    Web开发基础之CMDB系统开发之三
    Web开发基础之CMDB系统开发之二
    Ubuntu18.04升级至20.04
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13499632.html
Copyright © 2011-2022 走看看