# LeetCode 39. Combination Sum

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


Constraints:

• 1 <= candidates.length <= 30
• 1 <= candidates[i] <= 200
• Each element of candidate is unique.
• 1 <= target <= 500

Runtime: 3 ms, faster than 81.09% of Java online submissions for Combination Sum.

Memory Usage: 39.3 MB, less than 96.86% of Java online submissions for Combination Sum.

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

private void backtrack(int start, int[] candidates, int target, List<List<Integer>> result, List<Integer> temp) {
if (target == 0) {
} else if (target < 0) {
return;
}
for (int i = start; i < candidates.length; i++) {
backtrack(i, candidates, target - candidates[i], result, temp);
temp.remove(temp.size() - 1);
}
}
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

wenyq7

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-25
01-27 91

07-06 4225