[LeetCode]--39. Combination Sum

简介: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.The same repeated number may be chosen from C unlimit

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

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

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

我想好半天也没把递归搞清楚,在网上看了一个比较好的算法,跟着学了一遍,debug跟着递归走一走,感觉拨开迷雾一样。

public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if (candidates.length == 0)
            return res;
        List<Integer> temp = new ArrayList<Integer>();
        Arrays.sort(candidates);
        findSum(candidates, target, 0, 0, temp, res);
        return res;
    }

    private void findSum(int[] candidates, int target, int sum, int level,
            List<Integer> temp, List<List<Integer>> res) {
        if (sum == target) {
            res.add(new ArrayList<Integer>(temp));
            return;
        } else if (sum > target)
            return;
        else
            for (int i = level; i < candidates.length; i++) {
                temp.add(candidates[i]);
                findSum(candidates, target, sum + candidates[i], i, temp, res);
                temp.remove(temp.size() - 1);
            }
    }
目录
相关文章
|
5月前
Leetcode 377. Combination Sum IV
赤裸裸的完全背包,属于动态规划的范畴,大家有兴趣可以在网上搜索下其他资料。个人觉得动态规划还是比较难理解的,更难给别人讲清楚,所以这里我直接附上我的代码供大家参考。
25 0
LeetCode 39. Combination Sum
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。
55 0
LeetCode 39. Combination Sum
LeetCode 377. Combination Sum IV
给定一个由正整数组成且不存在重复数字的数组,找出和为给定目标正整数的组合的个数。
71 0
LeetCode 377. Combination Sum IV
LeetCode 216. Combination Sum III
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
79 0
LeetCode 216. Combination Sum III
LeetCode 216 Combination Sum III(Backtracking)(*)
版权声明:转载请联系本人,感谢配合!本站地址:http://blog.csdn.net/nomasp https://blog.csdn.net/NoMasp/article/details/51935033 翻译 找出所有的k个数字相加得到数字n的组合,只有1到9的数字可以被使用,并且每个组合间需要是不同的数字集。
714 0
LeetCode - 39. Combination Sum
39. Combination Sum  Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个待选集合s和一个数n,让你找出集合s中相加之和为n的所有组合.
806 0
LeetCode - 40. Combination Sum II
40. Combination Sum II  Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个待选集合s和一个数n,选出所有相加之和为n的组合.
970 0