题目允许把 2 用两次。那 [2,3,2] 要不要另外记一个答案?这题看的是组合,所以把数字排好,并约定只能向右选。
用 [2,3,6] 凑 7。选两个 2 后还差 3,这次可以从 2 开始继续挑,正好取到 3。如果先选了 3,后面的选择里已经没有 2,也就不会再生成同一组数字。
class Solution:
def combinationSum(self, candidates, target):
nums = sorted(candidates)
ans, path = [], []
def choose(start, rest):
if rest == 0:
ans.append(path.copy())
return
for j in range(start, len(nums)):
if nums[j] > rest:
break
path.append(nums[j])
choose(j, rest - nums[j])
path.pop()
choose(0, target)
return ans
设候选数为 k,最小值为 a,路径至多 D=⌊target/a⌋ 层。枚举规模可用 O(k^(D+1)) 作宽松上界,复制答案还与答案总长度有关。递归路径 O(D),排序副本 O(k)。正数条件保证剩余值越走越小。

