File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 1+ ## 77. Combinations
2+
3+ Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
4+
5+ You may return the answer in any order.
6+
7+
8+
9+ Example 1:
10+
11+ Input: n = 4, k = 2
12+ Output:
13+ [
14+ [ 2,4] ,
15+ [ 3,4] ,
16+ [ 2,3] ,
17+ [ 1,2] ,
18+ [ 1,3] ,
19+ [ 1,4] ,
20+ ]
21+ Example 2:
22+
23+ Input: n = 1, k = 1
24+ Output: [[ 1]]
25+
26+
27+ Constraints:
28+
29+ 1 <= n <= 20
30+ 1 <= k <= n
31+
32+ ``` python
33+ def combine (self , n : int , k : int ) -> List[List[int ]]:
34+ def gen_pattern (nums , k ):
35+ if k == 0 :
36+ return [[]]
37+ if k == 1 :
38+ return [[num] for num in nums]
39+
40+ res = []
41+ for i in range (len (nums)):
42+ perms = gen_pattern(nums[i+ 1 :], k- 1 )
43+ for p in perms:
44+ res.append([nums[i]] + p)
45+ return res
46+
47+ nums = list (range (1 , n+ 1 ))
48+ res = gen_pattern(nums, k)
49+ return res
50+ ```
51+
52+
53+ ```
54+ Runtime: 556 ms, faster than 37.57% of Python3 online submissions for Combinations.
55+ Memory Usage: 16.2 MB, less than 33.85% of Python3 online submissions for Combinations.
56+ ```
You can’t perform that action at this time.
0 commit comments