We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 29b12dd commit 374e0f9Copy full SHA for 374e0f9
Backtracking/combine.py
@@ -0,0 +1,39 @@
1
+# Given two integers n and k, return all possible combinations of k numbers
2
+# chosen from the range [1, n].
3
+
4
+# You may return the answer in any order.
5
6
+# Example 1:
7
+# Input: n = 4, k = 2
8
+# Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
9
10
+# Explanation: There are 4 choose 2 = 6 total combinations.
11
+# Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to
12
+# be the same combination.
13
14
+# Example 2:
15
+# Input: n = 1, k = 1
16
+# Output: [[1]]
17
18
+# Explanation: There is 1 choose 1 = 1 total combination.
19
20
21
+# Constraints:
22
+# 1 <= n <= 20
23
+# 1 <= k <= n
24
25
26
+from typing import List
27
+class Solution:
28
+ def combine(self, n: int, k: int) -> List[List[int]]:
29
+ ans = []
30
+ def dfs(s, path: list[int]):
31
+ if len(path) == k:
32
+ ans.append(path.copy())
33
+ return
34
+ for i in range(s, n+1):
35
+ path.append(i)
36
+ dfs(i+1, path)
37
+ path.pop()
38
+ dfs(1, [])
39
+ return ans
AltStyle によって変換されたページ (->オリジナル) / アドレス: モード: デフォルト 音声ブラウザ ルビ付き 配色反転 文字拡大 モバイル
0 commit comments