leetcode -- Combination -- 重点,求可能的0,1全排列

https://leetcode.com/problems/combinations/

思路1: 枚举0,1全排列。

这里的dfs tree: 见自己总结的notes

这里写图片描述

这题是经典的back tracking的题目。只要求出0,1全排列就行。利用backtracking的模板

这里的m是表示第m个元素

class Solution(object):

    def dfs(self, m, k, nums, subres, res):

        if sum(subres) == k:
            res.append([nums[i] for i,c in enumerate(subres) if c == 1])
            return
        elif m >= len(nums):
            return
        else:
            subres[m] = 0
            self.dfs(m+1, k, nums, subres, res)
            subres[m] = 1
            self.dfs(m+1, k, nums, subres, res)

    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        nums = [x + 1 for x in xrange(n)]
        subres = [0]*n
        res = []
        self.dfs(0, k, nums, subres,res)
        return res

思路2:另一种组合树

这里的dfs tree: 见自己总结的notes。 每个节点就是A数组的一个元素A[k],子节点(possible candidates)就是A[j], j>k

树的示意图

这里的start是表示第start个元素
pos表示现在的level

class Solution:
    def dfs(self,pos,k,n,start,ans,vec):
        if pos==k:
            temp=vec[:]
            ans.append(temp)
            return 
        for i in range(start,n+1):
            vec[pos]=i
            self.dfs(pos+1,k,n,i+1,ans,vec)
    # @return a list of lists of integers
    def combine(self, n, k):
        ans=[]
        vec=[0 for i in range(k)]
        self.dfs(0,k,n,1,ans,vec)
        return ans

还有其他解法参考:
没有太理解。再看看
http://www.cnblogs.com/zuoyuan/p/3757165.html
https://www.zybuluo.com/chanvee/note/61530
http://oldoldb.com/MyCodeForLeetCode/2014/07/28/Combinations/
http://blog.csdn.net/whiterbear/article/details/49075645

关于backtracking:
http://www.cnblogs.com/wuyuegb2312/p/3273337.html

自己重写code

class Solution(object):

    def dfs(self, depth, candidates, start, end, k, subres, res):

        if depth == k:
            res.append(subres)
        i = start
        while i < end:
            self.dfs(depth + 1, candidates, i + 1, end, k, subres + [candidates[i]], res)
            i += 1

    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        nums = [i + 1 for i in xrange(n)]
        res = []
        self.dfs(0, nums, 0, n, k, [], res)
        return res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值