• 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
    
    
    


  • 相关阅读:
    mq/mysql/redis/nginx常见服务&工具安装
    中断——中断描述符表的定义和初始化(二) (基于3.16-rc4)
    中断——中断描述符表的定义和初始化(一) (基于3.16-rc4)
    linux内核中与进程相关的数据结构(基于linux3.16-rc4)
    内核链表的应用
    ubuntu下做柯老师lab19-lab20实验问题总结
    在ns2.35中添加myevalvid框架
    在ns2.35下完成柯老师lab18实验
    windows编程socket问题
    如何高效利用GitHub
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13499632.html
Copyright © 2020-2023  润新知