-3

Input: Target sum

Output: count of all possible permutations with given sum from list [1,2,3]

Example input: 4 and corresponding output: 7

All possible pairs:

1, 1, 1, 1
1, 2, 1
1, 1, 2   
1, 3    
2, 1, 1    
2, 2    
3, 1

For these given permutations for explanation of output these all must be taken from [1,2,3] for any input.

Here is what I've tried so far:

def combinationSum(self, candidates, target):

    rests = [[] for _ in range(target)]
    for num in candidates:
        if num > target:
            continue
        else:
            rests[target - num].append([num])
        for cur_rest in range(target - 1, num - 1, -1):
            for result in rests[cur_rest]:
                rests[cur_rest - num].append(result + [num])

    return rests[0]

s=Solution()
c=[1,2,3]
t=int(input())
print(s.combinationSum(c,t))
Georgy
  • 12,464
  • 7
  • 65
  • 73

1 Answers1

0

As per solution suggested by @Tomerikoo, I have created solution with some modification.

    def combinationSum(self, candidates, target):
        # List for storing possible all sequence of permutations
        seq_list = []

        # This loop will generate all possible permutation for given candidates
        for i in range(1, target + 1):
           # Extend given list with cartesian product of given candidates

           # To calculate cartesian product set use itertools.product with candidates
           # with set size ranging from 1 to target number
           # This is necessary as we have to find all possible combinations
           seq_list.extend([p for p in itertools.product(candidates, repeat=i)])

        # Just select those sequence whose sum is target
        result = [seq for seq in seq_list if sum(seq) == target]

        # Return length of result set
        return len(result)

s=Solution() 
c=[1,2,3] 
t=int(input()) 
print(s.combinationSum(c,t))

Hope this help!!!

Parikshit Chalke
  • 3,745
  • 2
  • 16
  • 26