77.组合 回溯 队列 剪枝 python

在这里插入图片描述

思路

来源 https://leetcode-cn.com/problems/combinations/solution/hui-su-suan-fa-jian-zhi-python-dai-ma-java-dai-ma-/

  1. 采用回溯的方式,一课树的搜索路径记录情况,当搜索到叶节点的时候,就pop()出来,回到父节点,继续添加。
  2. 采取必要的剪枝情况,即 i 的上界情况,举个例子,画图计算就比较清晰
    在这里插入图片描述
class Solution(object):
    def dfs(self,n, k, begin, path, res):
        if len(path) == k:
            res.append(list(path))
            return res
        # 搜索起点的上界 + 接下来要选择的元素个数 - 1 = n
        # 搜索起点的上界 = n - (k - path.size()) + 1
        for i in range(begin,  n - (k - len(path)) + 1+1):
            path.append(i)
            Solution.dfs(self,n, k, i + 1, path, res)
            path.pop()
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        res = []
        if k <= 0 or n < k: return res
        # start at 1
        path = collections.deque()
        Solution.dfs(self,n, k, 1, path, res)
        return res


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值