DEV Community

Shailesh Kumar
Shailesh Kumar

Posted on

LeetCode September Day 12

Question -

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

All numbers will be positive integers.
The solution set must not contain duplicate combinations

*
Input: k = 3, n = 7
Output: [[1,2,4]]
*
Solution -

from itertools import combinations
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        return filter(lambda x: sum(x) == n, combinations(range(1, 10), r=k))

So, here I used python's library function combinations.
Combinations takes an iterable and other argument r denoting number of elements present in each combination, and returns all possible combinations.
For example combinations([1,2,3], r=2) will give [(1,2), (2,3), (1,3)].
Happy coding :) !

Top comments (0)