Python- Backtracking Solution-Beats 100.00% submissions


  • -2
    R
    import copy
    class Solution(object):
    def __init__(self):
        self.ans=[]
    def combinationSum3(self, k, n):
        """
        :type k: int
        :type n: int
        :rtype: List[List[int]]
        """
        def help(num,k,n,ans):
            if k==0 and n==0:
                self.ans.append(copy.deepcopy(ans))
                return
            elif num<=n and k>0 and n>0:
                for i in range(num+1,10):
                    ans.append(i)
                    help(i,k-1,n-i,ans)
                    del ans[len(ans)-1]
            else:
                return
        help(0,k,n,[])
        return self.ans

  • 0

    How often did you submit it? I just submitted it (after fixing your indentation error) five times and it got accepted in 44, 52, 44, 48 and 44 ms. And 44 ms beats 47%.


Log in to reply
 

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