Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 374e0f9

Browse files
#77. Combinations
1 parent 29b12dd commit 374e0f9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎Backtracking/combine.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /