leetcode77. 组合python

题目描述:

 题解:

1.按照题目给出的示例,相同数字按照不同顺序的排列组合看作一个。

2.题目中示例1的搜索过程如下:

3.实现思路:

<1>设置一个nums数组,共有n+1个数字,从0-n

<2>设置一个used数组,n+1个数字,初始化为全0,记录nums[i]是否已经被搜索(统一设置为n+1个数字之后,搜索范围从1-n)

<3>res保存最终结果,combination记录当前搜索过程,depth记录当前搜索树深度。

<4>定义一个dfs函数,如果当前depth=k,说明找到一个k个数字的组合,将combination加入res并返回。否则i从idx到n开始搜索,如果对应的used[i]=0,说明对应的nums[i]没有被使用,加入combination,然后进入下一层搜索。下一层从i+1开始避免重复!

 <5>回溯,将对应used重新设为0,从combination中删除对应数字。

class Solution(object):
    def combine(self, n, k):
        used = [0 for i in range(n+1)]
        nums = [0]
        for i in range(1,n+1):
            nums.append(i)
        res = []
        depth = 0
        def dfs(idx,used,depth,combination,res):
            if depth == k:
                res.append(combination[:])
                return
            for i in range(idx,n+1):
                if used[i]==0:
                    used[i]=1
                    combination.append(nums[i])
                    depth = depth+1
                    dfs(i+1,used,depth,combination,res)
                    depth = depth-1
                    used[i]=0
                    combination.pop()
        dfs(1,used,depth,[],res)
        return res

结果通过,但是执行用时很长。

改进版:如果当前剩余的可选数字已经不够了,就没有必要继续搜索了,利用n和当前搜索深度depth与k的关系判断。

class Solution(object):
    def combine(self, n, k):
        res = []
        depth = 0
        def dfs(array,idx,depth,combination,res):
            if depth == k:
                res.append(combination[:])
                return
            for i in range(idx,n):
                if n-idx<k-depth:
                    break
                combination.append(array[i])
                depth = depth+1
                dfs(array,i+1,depth,combination,res)
                depth = depth-1
                combination.pop()
        dfs(range(1,n+1),0,depth,[],res)
        return res

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值