Open azl397985856 opened 1 week ago
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
var result = [[Int]]()
var combination = [Int]()
func backtrack(_ start: Int, _ target: Int) {
if target == 0 {
result.append(combination)
return
}
if target < 0 {
return
}
for i in start..<candidates.count {
combination.append(candidates[i])
backtrack(i, target - candidates[i])
combination.removeLast()
}
}
backtrack(0, target)
return result
}
class Solution:
def combinationSum(
self, candidates: List[int], target: int
) -> List[List[int]]:
results = []
def backtrack(remain, comb, start):
if remain == 0:
# make a deep copy of the current combination
results.append(list(comb))
return
elif remain < 0:
# exceed the scope, stop exploration.
return
for i in range(start, len(candidates)):
# add the number into the combination
comb.append(candidates[i])
# give the current number another chance, rather than moving on
backtrack(remain - candidates[i], comb, i)
# backtrack, remove the number from the combination
comb.pop()
backtrack(target, [], 0)
return results
class Solution {
Set<List
39 组合总和
入选理由
暂无
题目地址
https://leetcode-cn.com/problems/combination-sum/
前置知识
题目描述
candidates 中的数字可以无限制重复被选取。
说明:
所有数字(包括 target)都是正整数。 解集不能包含重复的组合。 示例 1:
输入:candidates = [2,3,6,7], target = 7, 所求解集为: [ [7], [2,2,3] ] 示例 2:
输入:candidates = [2,3,5], target = 8, 所求解集为: [ [2,2,2,2], [2,3,3], [3,5] ]
提示:
1 <= candidates.length <= 30 1 <= candidates[i] <= 200 candidate 中的每个元素都是独一无二的。 1 <= target <= 500