【LeetCode 中等题】40-组合

题目描述:给定两个整数 n 和 k,返回 1 ... 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

解法1。使用库函数itertools.combinations()

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if n <= 0 or k > n:
            return []
        elif n == 1:
            return [[1]]
        import itertools
        res = []
        in_lst = [i+1 for i in range(n)]
        for lst in itertools.combinations(in_lst, k):
            if lst not in res:
                res.append(lst)
        return res

解法2。使用递归的方法。DFS深度优先搜索的方法,从1开始append到sublist里,如果sublist满足长度就append到大集合res里,返回到上一层记得pop出去,以及append的时候使用copy的方式sublist[:]而非直接appendsublist。

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        if n <= 0 or k > n:
            return
        elif n == 1:
            return [[1]]
        res = []
        sublist = []
        self.helper(n,k,1,sublist,res)
        return res
    
    def helper(self, n, k, start, sublist, res):
        if len(sublist) >= k:
            res.append(sublist[:])
            return
        for i in range(start, n+1):
            sublist.append(i)
            self.helper(n, k, i+1, sublist, res)
            sublist.pop()

参考链接:http://www.cnblogs.com/grandyang/p/4332522.html

猜你喜欢

转载自blog.csdn.net/weixin_41011942/article/details/85707399
今日推荐