动态规划
最大矩形 组合问题 最大路径 最长回文子串 爬楼梯
回溯
全排列 组合总和 N皇后
81. 组合总和 candidates
中的数字可以无限制重复被选取
- 【返回组合列表---回溯】
-
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: # 回溯,无重复元素,根据剩余值凑成目标 ans = [] # 收集逻辑为target == 0 def backtracking(index,path,target): # if index >= len(candidates): index 不会超过 candidate的长度 if target < 0: return if target == 0: # 收集条件 ans.append(path[:]) return for i in range(index,len(candidates)): # 注意可以重复收集 path.append(candidates[i]) # 做选择 backtracking(i,path,target-candidates[i]) path.pop() # 取消选择 backtracking(0,[],target) return ans
- 【返回组合个数---动态规划】
-
class Solution: def combinationSum4(self, nums: List[int], target: int) -> int: # 顺序不同视为不同组合,那么遍历的时候需要考虑for的两层顺序 # for 背包 # for 物品 。其中不保证物品先后顺序,从而得到的是排列数 # # for 物品 # for 背包,限制了物品的先后次序,从而得到的是组合数 dp = [0 for i in range(target+1)] dp[0] = 1 for j in range(1,target+1): for n in nums: if j-n>=0: dp[j] = dp[j] + dp[j-n] return dp[-1]
82. 组合总和II candidates
中的每个数字在每个组合中只能使用一次
- 【返回组合列表---回溯】
-
class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: # 回溯,注意去重逻辑 candidates.sort() n = len(candidates) ans = [] used = [False for i in range(n)] def backtracking(choice,path,aim,index): if aim == 0: ans.append(path.copy()) return if aim < 0: return for i in range(index,n): if used[i] == True: # 这个数被用过 continue # 不要手误写成return if i > 0 and choice[i] == choice[i-1] and used[i-1] == False: # 这里不能是used[i-1] == True,因为是顺序选取而不是可以倒着选 continue # 不要手误写成return used[i] = True path.append(choice[i]) backtracking(choice,path,aim-choice[i],i+1) # 注意这里是i+1而不是index+1 path.pop() used[i] = False backtracking(candidates,[],target,0) return ans
- 【返回组合个数---动态规划】
贪心
分糖果 跳跃游戏
class Solution:
def canJump(self, nums: List[int]) -> bool:
n, rightmost = len(nums), 0
for i in range(n):
if i <= rightmost:
rightmost = max(rightmost, i + nums[i])
if rightmost >= n - 1:
return True
return False