思路
来源 https://leetcode-cn.com/problems/combinations/solution/hui-su-suan-fa-jian-zhi-python-dai-ma-java-dai-ma-/
- 采用回溯的方式,一课树的搜索路径记录情况,当搜索到叶节点的时候,就pop()出来,回到父节点,继续添加。
- 采取必要的剪枝情况,即 i 的上界情况,举个例子,画图计算就比较清晰
class Solution(object):
def dfs(self,n, k, begin, path, res):
if len(path) == k:
res.append(list(path))
return res
# 搜索起点的上界 + 接下来要选择的元素个数 - 1 = n
# 搜索起点的上界 = n - (k - path.size()) + 1
for i in range(begin, n - (k - len(path)) + 1+1):
path.append(i)
Solution.dfs(self,n, k, i + 1, path, res)
path.pop()
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
res = []
if k <= 0 or n < k: return res
# start at 1
path = collections.deque()
Solution.dfs(self,n, k, 1, path, res)
return res