Skip to content

Commit ecf4b16

Browse files
committed
[LeetCode Sync] Runtime - 0 ms (100.00%), Memory - 17.9 MB (16.23%)
1 parent 64bd1c0 commit ecf4b16

File tree

2 files changed

+67
-0
lines changed

2 files changed

+67
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
<p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p>
2+
3+
<ul>
4+
<li>Only numbers <code>1</code> through <code>9</code> are used.</li>
5+
<li>Each number is used <strong>at most once</strong>.</li>
6+
</ul>
7+
8+
<p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p>
9+
10+
<p>&nbsp;</p>
11+
<p><strong class="example">Example 1:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> k = 3, n = 7
15+
<strong>Output:</strong> [[1,2,4]]
16+
<strong>Explanation:</strong>
17+
1 + 2 + 4 = 7
18+
There are no other valid combinations.</pre>
19+
20+
<p><strong class="example">Example 2:</strong></p>
21+
22+
<pre>
23+
<strong>Input:</strong> k = 3, n = 9
24+
<strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]]
25+
<strong>Explanation:</strong>
26+
1 + 2 + 6 = 9
27+
1 + 3 + 5 = 9
28+
2 + 3 + 4 = 9
29+
There are no other valid combinations.
30+
</pre>
31+
32+
<p><strong class="example">Example 3:</strong></p>
33+
34+
<pre>
35+
<strong>Input:</strong> k = 4, n = 1
36+
<strong>Output:</strong> []
37+
<strong>Explanation:</strong> There are no valid combinations.
38+
Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination.
39+
</pre>
40+
41+
<p>&nbsp;</p>
42+
<p><strong>Constraints:</strong></p>
43+
44+
<ul>
45+
<li><code>2 &lt;= k &lt;= 9</code></li>
46+
<li><code>1 &lt;= n &lt;= 60</code></li>
47+
</ul>
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution:
2+
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
3+
result, temp = [], []
4+
5+
def dfs(i: int, j: int):
6+
if j == 0:
7+
if len(temp) == k:
8+
result.append(temp[:])
9+
return
10+
11+
if i > 9 or i > j or len(temp) > k:
12+
return
13+
14+
temp.append(i)
15+
dfs(i + 1, j - i)
16+
temp.pop()
17+
dfs(i + 1, j)
18+
19+
dfs(1, n)
20+
return result

0 commit comments

Comments
 (0)