美文网首页
组合总和

组合总和

作者: shiguangfeixu | 来源:发表于2021-03-18 23:47 被阅读0次

Algorithm

39. Combination Sum

Description

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the frequency of at least one of the chosen numbers is different.

It is guaranteed that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Example 1:

Input: candidates = [2,3,6,7], target = 7
Output: [[2,2,3],[7]]
Explanation:
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.

Example 2:

Input: candidates = [2,3,5], target = 8
Output: [[2,2,2,2],[2,3,3],[3,5]]

Example 3:

Input: candidates = [2], target = 1
Output: []

Example 4:

Input: candidates = [1], target = 1
Output: [[1]]

Example 5:

Input: candidates = [1], target = 2
Output: [[1,1]]

Constraints:

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • All elements of candidates are distinct.
  • 1 <= target <= 500

Solution

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> list = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(list, new ArrayList<>(), candidates, target, 0);
        return list;
    }

    public 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]);
                // 从i开始因为可以有重复元素
                backtrack(list, tempList, nums, remain - nums[i], i);
                // 能够跳出循环说明当前remain<0, 需要去掉最后一个扣减的元素
                tempList.remove(tempList.size() - 1);
            }
        }
    }
}

相关文章

  • 组合总和

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可...

  • 组合总和

  • 组合总和

    Algorithm 39. Combination Sum[https://leetcode.com/proble...

  • LeetCode:组合总和

    组合总和 题目叙述: 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 cand...

  • 2018-08-13 LeetCode回溯算法(组合总和)总结

    组合总和candidates 中的数字可以无限制重复被选取 组合总和 IIcandidates 中的每个数字在每个...

  • 39. 组合总和

    39. 组合总和 很慢的dfs

  • 39. 组合总和

    给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可...

  • leetcode 39 组合总和

    今天很奇怪,我用的是dfs,AC代码是 但是前面一直用下面的代码,过不了 后来发现我这样写会改变sum的值,下次要...

  • 39.组合总和

    题目给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所...

  • 39.组合总和

网友评论

      本文标题:组合总和

      本文链接:https://www.haomeiwen.com/subject/fmumcltx.html