【LEETCODE】77-Combinations [Python]

来源:互联网 发布:淘宝网div css布局实例 编辑:程序博客网 时间:2024/05/22 08:01

Given two integers n and k, return all possible combinations ofk 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




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


0 0
原创粉丝点击