Leetcode 77. 组合(Python3)

77. 组合

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

示例:

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

DFS:

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        res = []
        self.dfs(range(1,n+1),k,res,[])
        return res
    def dfs(self,nums,k,res,path):
        if k > len(nums):
            return 
        #终止条件
        elif k == 0: 
            res.append(path)
        else:
            for i in range(len(nums)):
                self.dfs(nums[i+1:],k-1,res,path+[nums[i]])

调包:pythonic解法

class Solution(object):
    import itertools
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        return list(itertools.combinations(range(1,n+1),k))

猜你喜欢

转载自blog.csdn.net/qq_38575545/article/details/87519089
今日推荐