题目:
思路
这道题需要找出所有组合,因此需要使用暴力搜索的方法。而每个答案中数字的个数一定,因此可以使用回溯法。这里我使用的python语言可以直接进行列表的“加减”运算,所以在递归的函数中不用指定搜索过程中存储答案的列表变量,而是直接将当前存储答案的列表做加法运算,作为下一个搜索函数的参数。而为了保证不重复,在搜索完当前方案的最后一个数后,将列表中的数字排序并转换成字符串,使用一个全局map字典来判重。
代码
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
ans=[]
vis=[0 for i in range(10)]
dic={}
def dfs(cur,templist,summ):
nonlocal k,n,ans,dic
if summ==n and cur==k:
tempstr=[]
for i in templist:
tempstr.append(str(i))
tempstr.sort()
tempstr=''.join(tempstr)
if not dic.get(tempstr,0):
ans.append(templist)
dic[tempstr]=1
return
if cur>k:
return
for i in range(1,10):
if not vis[i] and summ+i<=n:
vis[i]=1
dfs(cur+1,templist+[i],summ+i)
vis[i]=0
dfs(0,[],0)
return ans