题目
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
res = []
def com(i, tmp_arr):
if len(tmp_arr) == k:
res.append(tmp_arr)
if i > n:
return
for j in range(i, n + 1):
com(j + 1, tmp_arr + [j])
com(1, [])
return res
博客围绕力扣题目展开,给定两个整数n和k,需返回1到n中所有可能的k个数的组合,并给出示例。该问题可通过回溯、递归方法解决,虽未给出代码,但明确了问题及来源。

488

被折叠的 条评论
为什么被折叠?



