Easy Recursive Python Code


  • 0
    W
    class Solution:
        # @return a list of lists of integers
        def combine(self, n, k):
            if n<k:
                return [[]]
            elif k==1:
                tot=[]
                x=[0]
                for i in range(1,n+1):
                    x[0]=i
                    tot.append([x[0]])
                return tot
            elif n==k:
                tot=[]
                x=[]
                for i in range(1,n+1):
                    x.append(i)
                tot.append(x)
                return tot
            else:
                tot=[]
                for x in self.combine(n-1,k-1):
                    y=x+[n]
                    tot.append(y)
                return tot+self.combine(n-1,k)

Log in to reply
 

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