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?


  • 2
    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.


  • 1
    M

    @yu_zhoujr said in Python recursive solution:

    @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.

    its a deep copy, try it youself


Log in to reply
 

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