Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 13951

How to generate unique sequences?

$
0
0

I am trying to solve 377. Combination Sum 4.

Output: 7Explanation:The possible combination ways are:(1, 1, 1, 1)(1, 1, 2)(1, 2, 1)(1, 3)(2, 1, 1)(2, 2)(3, 1)

Here's my solution so far:

class Solution(object):    def combinationSum4(self, nums, target):"""        :type nums: List[int]        :type target: int        :rtype: int"""        result = []        def dfs(i, curr, total):            # print(i)            if total==target:                result.append(curr[::])                return            if total>target or i>=len(nums):                return            curr.append(nums[i])            dfs(i, curr, total+nums[i])            curr.pop()            dfs(i+1,curr,total)        dfs(0,[],0)        print(result)        return len(result)

It generates only one of (1,1,2),(1,2,1)(2,1,1) solutions or one of (1,3)(3,1). I am not sure how to construct the recursive tree such that all solutions would be produced. In general, how to think about building recursive trees for different solutions, like unique combinations (which would contain just one of the above possible solutions), unique sequences etc.? Any help is greatly appreciated!


Viewing all articles
Browse latest Browse all 13951

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>