给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。
说明:
所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。
def combinationSum( candidates, target: int) :
res=[];
c_l=len(candidates);
def find(output,newTarget,i,c_l):
sorted(output):同一个数组,不同顺序是一样的
if newTarget==0 and sorted(output) not in res:
res.append(sorted(output));
return;
用来跳过这一k;防止重复计算当前值
if i>=c_l:return;
防止重复计算上一步的值;从上一步的i的i+1开始循环
for k in range(i,c_l):
now=candidates[k]
new_target=newTarget-now;
if new_target>=0:
用来跳过这一k;防止重复计算当前值
find(output+[now],new_target,k+1,c_l)
find([],target,0,c_l);
return res
candidates=[2,3,6,7,5,6,1];
print(combinationSum(candidates,7))
[[2, 5], [1, 6], [7]]
candidates 中的数字可以无限制重复被选取。
def combinationSum2( candidates, target: int) :
res=[];
c_l=len(candidates);
def find(output,newTarget,i,c_l):
if newTarget==0 and sorted(output) not in res:
res.append(sorted(output));
return;
为了可以重复使用上一步的值:就注释了下面的
for k in range(i,c_l):
now=candidates[k]
new_target=newTarget-now;
if new_target >=0:
k为当前index,为了可以重复使用当前值
find(output+[now],new_target,k,c_l)
find([],target,0,c_l);
return res
candidates=[2,3,6,7,5,1];
print(combinationSum2(candidates,7))
[
[1, 2, 2, 2], [2, 2, 3], [1, 1, 1, 2, 2],
[1, 1, 2, 3], [2, 5],
[1, 1, 1, 1, 1, 2], [1, 3, 3],
[1, 1, 1, 1, 3], [1, 6], [7], [1, 1, 5],
[1, 1, 1, 1, 1, 1, 1]
]