Skip to content

Commit 7de6815

Browse files
216. Combination Sum III
Difficulty: Medium 18 / 18 test cases passed. Runtime: 32 ms Memory Usage: 13.8 MB
1 parent 7e81f4f commit 7de6815

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Medium/216.CombinationSumIII.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Find all possible combinations of k numbers that add up to a number n,
3+
given that only numbers from 1 to 9 can be used and each combination should
4+
be a unique set of numbers.
5+
6+
Note:
7+
- All numbers will be positive integers.
8+
- The solution set must not contain duplicate combinations.
9+
10+
Example:
11+
Input: k = 3, n = 7
12+
Output: [[1,2,4]]
13+
14+
Example:
15+
Input: k = 3, n = 9
16+
Output: [[1,2,6], [1,3,5], [2,3,4]]
17+
"""
18+
#Difficulty: Medium
19+
#18 / 18 test cases passed.
20+
#Runtime: 32 ms
21+
#Memory Usage: 13.8 MB
22+
23+
#Runtime: 32 ms, faster than 68.72% of Python3 online submissions for Combination Sum III.
24+
#Memory Usage: 13.8 MB, less than 62.64% of Python3 online submissions for Combination Sum III.
25+
26+
class Solution:
27+
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
28+
if k > n:
29+
return
30+
self.result = []
31+
self.backtracking(k, n)
32+
return self.result
33+
34+
def backtracking(self, k, n, start = 1, summ = 0, count = 0, nums = []):
35+
if count > k:
36+
return
37+
if count == k and summ == n:
38+
result = []
39+
result.extend(nums)
40+
self.result.append(result)
41+
return
42+
for num in range(start, 10):
43+
if summ + num > n:
44+
break
45+
nums.append(num)
46+
self.backtracking(k, n, num+1, summ+num, count+1, nums)
47+
nums.pop()

0 commit comments

Comments
 (0)