zoukankan      html  css  js  c++  java
  • 39. Combination Sum 凑出一个和,可以重复用元素(含duplicates)

    Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

    The same repeated number may be chosen from candidates unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [2,3,6,7], target = 7,
    A solution set is:
    [
      [7],
      [2,2,3]
    ]
    

    Example 2:

    Input: candidates = [2,3,5], target = 8,
    A solution set is:
    [
      [2,2,2,2],
      [2,3,3],
      [3,5]
    ]

    可以不从第0位开始,直接从start开始。DFS中应该有start这个参数

    循环里面当然是用i,不是start

    需要考虑currentSum > target然后就会直接return ;的这种情况

    和subset、全排列不同,这里的元素可以重复用。所以不需要
    if(temp.contains(nums[i])) continue;
    
    
    
    
    class Solution {
        public List<List<Integer>> combinationSum(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++) {
                    temp.add(nums[i]);
                    backtrace(nums, temp, i, currentSum + nums[i],
                             target, results);
                    temp.remove(temp.size() - 1);
                }
            }
        }
    }
    View Code


  • 相关阅读:
    【转】php三种工具pecl pear composer的区别
    【转】Git使用详细教程
    【转】chrome Network 过滤和高级过滤
    Python3第三方组件最新版本追踪实现
    Python3版本号比较代码实现
    模糊测试工具设计思路浅谈
    Python3+WebSockets实现WebSocket通信
    Python3+PyCryptodome实现各种加密算法教程
    HTTP漫谈
    Python3+Robot Framework+RIDE安装使用教程
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13488039.html
Copyright © 2011-2022 走看看