Fairly short DFS soluton


  • 0
    D
    def combinationSum3(self, k, n):
        return [s for s in self.search(list(range(1,n+1)), n) if len(s) == k]
    def search(self, nums, n):
        if not n:
            return [[]]
        ans = []
        for i in xrange(len(nums)):
            if nums[i] > n:
                break
            for s in self.search(nums[i+1:], n-nums[i]):
                ans.append([nums[i]]+s)
        return ans

Log in to reply
 

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