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

    这道题应该是用remain这个数是否等于0来判断才对,而不是permutations的用长度来判断
    backtrack(list, tempList, nums, remain - nums[i], i); 是i不是i + 1,因为此处可以重用相同的元素

    class Solution {
    public List<List<Integer>> combinationSum(int[] nums, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(nums);
        backtrack(list, new ArrayList<>(), nums, target, 0);
        return list;
    }
    
    private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
        if(remain < 0) return;
        else if(remain == 0) list.add(new ArrayList<>(tempList));
        else{ 
            for(int i = start; i < nums.length; i++){
                tempList.add(nums[i]);
                backtrack(list, tempList, nums, remain - nums[i], i); // not i + 1 because we can reuse same elements
                tempList.remove(tempList.size() - 1);
            }
        }
    }
    }
    View Code
    
    
    
     
  • 相关阅读:
    java基础入门-arraylist存储开销
    java基础入门-iterator迭代器与集合下标的使用
    java基础入门-泛型(1)-为什么需要使用泛型?
    vue路由懒加载
    js防抖和节流
    vue 生命周期函数详解
    createElement 函数
    vue中Runtime-Compiler和Runtime-only的区别
    箭头函数以及this指向问题
    webpackES6语法转ES5语法
  • 原文地址:https://www.cnblogs.com/immiao0319/p/13217151.html
Copyright © 2011-2022 走看看