【LEETCODE】77-Combinations [Python]

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,

If n = 4 and k = 2, a solution is:

[

  [2,4],

  [3,4],

  [2,3],

  [1,2],

  [1,3],

  [1,4],

]


题意:

给两个整数 n,k,返回 1 to n 中取 k 个数字的所有可能的组合


思路:

DFS


参考:

http://www.cnblogs.com/zuoyuan/p/3757165.html


【LEETCODE】77-Combinations [Python]_第1张图片


Python

class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """
        
        ans=[]
        self.count=0
        
        def dfs(start,nums):
        
            if self.count==k:
                ans.append(nums)
                return
            
            for i in range(start,n+1):
                self.count+=1
                dfs(i+1,nums+[i])
                self.count-=1
        
        dfs(1,[])
        
        return ans


你可能感兴趣的:(LEETCODE)