Skip to content

Commit cc4f066

Browse files
committed
Combination Sum III
1 parent 364f101 commit cc4f066

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed
+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
'''Leetcode- https://leetcode.com/problems/combination-sum-iii/'''
2+
'''
3+
Find all valid combinations of k numbers that sum up to n such that the following conditions are true:
4+
5+
Only numbers 1 through 9 are used.
6+
Each number is used at most once.
7+
Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order.
8+
9+
10+
11+
Example 1:
12+
13+
Input: k = 3, n = 7
14+
Output: [[1,2,4]]
15+
Explanation:
16+
1 + 2 + 4 = 7
17+
There are no other valid combinations.
18+
'''
19+
20+
21+
def combinationSum3(k, n):
22+
res = []
23+
24+
def backtrack(cur, n, start):
25+
if k == len(cur):
26+
if n == 0:
27+
res.append(cur.copy())
28+
return
29+
for i in range(start, 10):
30+
cur.append(i)
31+
backtrack(cur, n-i, i+1)
32+
cur.pop()
33+
backtrack([], n, 1)
34+
return res

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,6 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1515
- [x] [Combinations](Backtracking/77-Combinations.py)
1616
- [x] [Combination Sum](Backtracking/39-Combination-Sum.py)
1717
- [x] [Combination Sum II](Backtracking/40-Combination-Sum-II.py)
18+
- [x] [Combination Sum III](Backtracking/216-Combination-Sum-III.py)
1819

1920

0 commit comments

Comments
 (0)