Easy Python Solution 245ms


  • 0
    class Solution(object):
        def combine(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: List[List[int]]
            """
            if n < k:
                return []
            if n == k:
                return [range(1, n+1)]
            res = []
            def ret(res_one, n, k):
                if k == 0:
                    res.append(res_one)
                    return
                for v in range(n, k-1, -1):
                    ret(res_one + [v], v-1, k-1)
            ret([], n, k)
            return res
    

  • 0
    H

    @MU001999 amazing! I write a similar one but TLE. maybe nums[i+1:] cost a lot?

        if k == 0 or n < 1:
            return []
        if k == 1:
            return [[i+1] for i in range(n)
    
        nums = [i+1 for i in range(n)]
        res = []
        def f(nums, lst, k):
            if k == 0:
                res.append(lst)
                return
            for i, v in enumerate(nums):
                f(nums[i+1:], lst+[v], k-1)
            return
    
        f(nums, [], k)
        return res

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.