Python recursive solution


  • 3
    G
    class Solution:
        # @return a list of lists of integers
        # 9:14
        def __init__(self):
            self.output = []
    
        def combine(self, n, k, pos=0, temp=None):
            temp = temp or []
            
            if len(temp) == k:
                self.output.append(temp[:])
                return
    
            for i in range(pos, n):
                temp.append(i+1)
                self.combine(n, k, i+1, temp)
                temp.pop()
            
            return self.output

  • 0
    D

    Hey, I liked your code and ran it, much better to understand .. but I didnt get self.output.append(temp[:]) ... not ofcourse appending just temp, isnt working for me. I am not able to find any reference on why?


  • 1
    N

    Don't know what happened, but I got TLE with the same code.


  • 0
    Y

    @dharaB self.output.append(temp[:]) will make a shallow copy of array temp, if you don't specify this, and pass in just temp, then you will change the reference of temp, and all of your return value will be modified.


Log in to reply
 

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