Find all unique combinations
Problem to find all the combination which sum is k value.
Example-1:
Input : n = [ 1, 2, 3, 4, 5] k = 5 Output : [[2, 3], [1, 4], [5]]
Example-2:
Input : n = [ 10, 1, 2, 7, 6, 1, 5] k = 8 Output : [[1, 7], [2, 6], [1, 2, 5], [1, 1, 6]]
Solution
from itertools import permutations n = [ 1, 2, 3, 4, 5] k = 5 a = sorted(n) l = [] z = [] h = [] for x in a: if(x <= k): l.append(x) else: break for i in range(len(l),0,-1): b = list(permutations(l,i)) for j in b: if(sum(j) == k): z.append(j) c = set(z) for u in c: u = sorted(u) u = tuple(u) h.append(u) d = list(set(h)) e = [list(v) for v in d] print(e)
Output
[[2, 3], [1, 4], [5]]