● 理论基础
● 77. 组合
一层递归就是一层for循环
回溯三部曲:1.递归函数参数的返回值
2.确定终止条件
3.单层递归的逻辑
#伪代码
二维数组 result
一维数组 path
void backtracking(n,k,startindex){
if(path.size==k):
result.push(path);
return
for(i=startindex;i<=n;i++){
path.push(i);
backtracking(n,k,i+1);
path.pop();}
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
#回溯算法
res=[]
path=[]
def backtracking(n,k,startindex):
if len(path)==k:
res.append(path[:])
return
for i in range(startindex,n+1):
path.append(i)
backtracking(n,k,i+1)
path.pop()
backtracking(n,k,1)
return res
#伪代码
#剪枝
二维数组 result
一维数组 path
void backtracking(n,k,startindex){
if(path.size==k):
result.push(path);
return
for(i=startindex;i<=n-(k-path.size)+1;i++){
path.push(i);
backtracking(n,k,i+1);
path.pop();}
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
#回溯算法
#剪枝
res=[]
path=[]
def backtracking(n,k,startindex):
if len(path)==k:
res.append(path[:])
return
for i in range(startindex,n-(k-len(path))+2):
path.append(i)
backtracking(n,k,i+1)
path.pop()
backtracking(n,k,1)
return res