Skip to content

Commit 64bd1c0

Browse files
committed
[LeetCode Sync] Runtime - 135 ms (63.29%), Memory - 59.7 MB (26.74%)
1 parent 568415b commit 64bd1c0

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<p>Given two integers <code>n</code> and <code>k</code>, return <em>all possible combinations of</em> <code>k</code> <em>numbers chosen from the range</em> <code>[1, n]</code>.</p>
2+
3+
<p>You may return the answer in <strong>any order</strong>.</p>
4+
5+
<p>&nbsp;</p>
6+
<p><strong class="example">Example 1:</strong></p>
7+
8+
<pre>
9+
<strong>Input:</strong> n = 4, k = 2
10+
<strong>Output:</strong> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
11+
<strong>Explanation:</strong> There are 4 choose 2 = 6 total combinations.
12+
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
13+
</pre>
14+
15+
<p><strong class="example">Example 2:</strong></p>
16+
17+
<pre>
18+
<strong>Input:</strong> n = 1, k = 1
19+
<strong>Output:</strong> [[1]]
20+
<strong>Explanation:</strong> There is 1 choose 1 = 1 total combination.
21+
</pre>
22+
23+
<p>&nbsp;</p>
24+
<p><strong>Constraints:</strong></p>
25+
26+
<ul>
27+
<li><code>1 &lt;= n &lt;= 20</code></li>
28+
<li><code>1 &lt;= k &lt;= n</code></li>
29+
</ul>
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def combine(self, n: int, k: int) -> List[List[int]]:
3+
result = []
4+
temp = []
5+
6+
def dfs(i: int):
7+
if len(temp) == k:
8+
result.append(temp[:])
9+
return
10+
if i > n:
11+
return
12+
temp.append(i)
13+
dfs(i + 1)
14+
temp.pop()
15+
dfs(i + 1)
16+
17+
dfs(1)
18+
return result

0 commit comments

Comments
 (0)