77. Combinations
Medium
218281Add to ListShare
Given two integers n
and k
, return all possible combinations of k
numbers out of the range [1, n]
.
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Example 2:
Input: n = 1, k = 1
Output: [[1]]
Constraints:
1 <= n <= 20
1 <= k <= n
我的:440ms
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
"""
解题思路:搜索题
"""
result = []
def dfs(i: int, cur_list: List[int]) -> None:
if len(cur_list) >= k:
result.append(list(cur_list))
return
if i > n:
return
for j in range(i, n + 1):
cur_list.append(j)
dfs(j + 1, cur_list)
cur_list.pop()
dfs(1, [])
return result
参考答案1:76ms
from itertools import combinations
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
return list(combinations([i for i in range(1,n+1)],k))
参考答案2:100ms
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
def helper(n,k,start):
# base case: need only one element
if k == 1:
return [[i] for i in range(start,n+1)]
result = []
for i in range(start,n-k+2):
L = helper(n,k-1,i+1)
for j in L:
result.append([i]+j)
return result
return helper(n,k,1)