给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
这个主要思想就是回溯法,在回溯函数调用之后去掉一个答案,回溯调用之前加入一个答案
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
ress = []
def backtrack(res = [],begin = 1):
if len(res) == k:
ress.append(res[:])
for i in range(begin,n+1):
res.append(i)
backtrack(res,i+1)
res.pop()
backtrack()
return ress