题目
描述
给出一组候选数 c 和一个目标数 t ,找出候选数中起来和等于 t 的所有组合。
c 中的每个数字在一个组合中只能使用一次。
注意:
- 题目中所有的数字(包括目标数 t )都是正整数
- 组合中的数字要按非递减排序
- 结果中不能包含重复的组合
- 组合之间的排序按照索引从小到大依次比较,小的排在前面,如果索引相同的情况下数值相同,则比较下一个索引。
要求:空间复杂度 O(n!) , 时间复杂度 O(n!)
思路
深度优先遍历,参考全排列。可选状态要设定好。
代码
python版本:
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param num int整型一维数组
# @param target int整型
# @return int整型二维数组
#
class Solution:
def combinationSum2(self , num: List[int], target: int) -> List[List[int]]:
# write code here
cur = []
store = num
res = []
store.sort()
def dfs(cur, store, target):
nonlocal res
if(target==0):
res.append(cur)
length = len(store)
for i in range(length):
if(i!=0 and store[i]==store[i-1]):#去重
continue
if(store[i]<=target):#如何减支?
dfs(cur+[store[i]], store[i+1:], target-store[i])
dfs(cur, store, target)
return res
c++版本:
无