Share My Simple AC Python Solution


  • 0
    M

    Two backtracking point

    1. If k > i (i.e., there are no enough number to fill k space), return.
    2. If k == 0, we have enough elements
    class Solution(object):
        def combine(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: List[List[int]]
            """
            result = []
    
            def dfs(stack, num, k):
                if k == 0:
                    result.append(stack)
                    return
    
                for i in reversed(xrange(1, num + 1)):
                    if k > i: break
                    dfs(stack + [i], i - 1, k - 1)
    
            dfs([], n, k)
            return result
    

Log in to reply
 

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