title: LEETCODE-DAY24
date: 2024-03-15 21:40:07
tags:
今日内容:回溯算法
T1
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res=[]
self.backtracking(n,k,1,[],res)
return res
def backtracking(self,n,k,idx,path,res):
if len(path)==k:
res.append(path.copy())
return
for i in range(idx,n+1):
path.append(i)
self.backtracking(n,k,i+1,path,res)
path.pop()
剪枝优化
k-len(path)=n-i+1([i,n]中的个数)
i>n+1-(k-len(path))时,[i,n]中数的个数不足以使path长度到达k,故不需遍历
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res=[]
self.backtracking(n,k,1,[],res)
return res
def backtracking(self,n,k,idx,path,res):
if len(path)==k:
res.append(path.copy())
return
for i in range(idx,n-k+len(path)+2):
path.append(i)
self.backtracking(n,k,i+1,path,res)
path.pop()
LC example:
class Solution:
def combine(self, n: int, k: int) -> List[List[int]]:
res = []
tmp = []
for i in range(1,k+1):
tmp.append(i)
end = []
for i in range(n-k+1,n+1):
end.append(i)
while tmp != end:
res.append(tmp[:])
for i in range(1,k+1):
if tmp[-i] == n + 1 -i:
continue
tmp[k-i] += 1
for j in range(k-i+1,k):
tmp[j] = tmp[j-1] + 1
break
res.append(end[:])
return res