39. Combination Sum

深碍√TFBOYSˉ_ 2022-03-07 03:35 308阅读 0赞

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:

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

Example 2:

  1. Input: candidates = [2,3,5], target = 8,
  2. A solution set is:
  3. [
  4. [2,2,2,2],
  5. [2,3,3],
  6. [3,5]
  7. ]

难度:medium

题目:给定一无重复元素的集合和一指定数,找出所有由数组内元素之和为该数的序列。每个元素都可以被无限次使用。
注意:所以元素都为正整数包括给定的整数。答案不允许有重复的组合。

思路:递归

Runtime: 9 ms, faster than 81.90% of Java online submissions for Combination Sum.
Memory Usage: 29.6 MB, less than 16.71% of Java online submissions for Combination Sum.

  1. class Solution {
  2. public List<List<Integer>> combinationSum(int[] candidates, int target) {
  3. Arrays.sort(candidates);
  4. List<List<Integer>> result = new ArrayList();
  5. combinationSum(candidates, 0, target, 0, new Stack<Integer>(), result);
  6. return result;
  7. }
  8. public void combinationSum(int[] cs, int idx, int target, int sum, Stack<Integer> stack, List<List<Integer>> result) {
  9. if (sum == target) {
  10. result.add(new ArrayList(stack));
  11. return;
  12. }
  13. for (int i = idx; i < cs.length; i++) {
  14. if (sum + cs[i] <= target) {
  15. stack.push(cs[i]);
  16. combinationSum(cs, i, target, sum + cs[i], stack, result);
  17. stack.pop();
  18. }
  19. if (sum + cs[i] >= target) break;
  20. }
  21. }
  22. }

发表评论

表情:
评论列表 (有 0 条评论,308人围观)

还没有评论,来说两句吧...

相关阅读