File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change 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)
Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments