LeetCode 216. 组合总和 III(回溯法)

题目:

思路

  这道题需要找出所有组合,因此需要使用暴力搜索的方法。而每个答案中数字的个数一定,因此可以使用回溯法。这里我使用的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

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值