您的位置:首页 > 其它

Leetcode: Combinations

2015-09-09 06:04 344 查看

Question

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],

]

Show Tags

Show Similar Problems

Solution

Get idea from here.

In the recursion function, it is efficient to prun.

[code]class Solution(object):
    def combine(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: List[List[int]]
        """

        res, cur = [], []
        if n<0 and n<k:
            return res

        self.helper(n, k, 1, cur, res)
        return res

    def helper(self, n, k, start, cur, res):

        if len(cur)==k:
            res.append(cur)
            return

        for elem in range(start,n+1):
            self.helper(n, k, elem+1, cur+[elem], res)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: