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 605bad8

Browse files
Combinations
1 parent 5bb59b5 commit 605bad8

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

‎Backtracking/77-Combinations.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'''Leetcode- https://leetcode.com/problems/combinations/'''
2+
'''
3+
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].
4+
5+
You may return the answer in any order.
6+
7+
Example 1:
8+
9+
Input: n = 4, k = 2
10+
Output:
11+
[
12+
[2,4],
13+
[3,4],
14+
[2,3],
15+
[1,2],
16+
[1,3],
17+
[1,4],
18+
]
19+
'''
20+
def combine(n, k):
21+
result = []
22+
23+
def backtrack(start,comb):
24+
if len(comb) == k:
25+
result.append(comb.copy())
26+
return
27+
28+
for i in range(start,n+1):
29+
comb.append(i)
30+
backtrack(i+1,comb)
31+
comb.pop()
32+
33+
backtrack(1,[])
34+
return result
35+
36+
#T: O(k.n^k)
37+
#T: O(k. n!/(n-k)!k!)
38+
#S: O(n)

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
1212
- [x] [Subsets-II](Backtracking/78-Subsets.py)
1313
- [x] [Permutations](Backtracking/46-Permutations.py)
1414
- [x] [Permutations II](Backtracking/47-Permutations-II.py)
15+
- [x] [Combinations](Backtracking/77-Combinations.py)
1516

0 commit comments

Comments
(0)

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