Anybody solve this question by python


  • 0
    S

    Anybody solve this problem by Python? My python codes always got the trouble:

    def combine(n, k):
    if n==0:
        return []
    elif k==0:
        return []
    elif n<k:
        return []
    else:
        combine_list=[]
        def recursive_help(n, k, sub_list, start):
            if len(sub_list)==k:
                print(sub_list)
                combine_list.append(sub_list)
                return
                print(combine_list)
            elif start<=n:
                for i in range(start, n+1):
                    sub_list+=[i]
                    recursive_help(n, k, sub_list, i+1)
                    sub_list.pop()                
        
        recursive_help(n, k, [], 1)
        return combine_list

  • 0
    C

    Here is my solution:

    def combine(self, n, k):
    
        ans = []
    
        def helper(start, end, count, combo):
            if count == 0:
                ans.append(combo[:])
                return
            for i in range(start, end-count+2):
                helper(i+1, end, count-1, combo+[i])
    
        helper(1, n, k, [])
        return ans

Log in to reply
 

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