动态规划详解(leetcode例题+解析)python
程序员文章站
2022-05-21 11:59:23
动态规划详解(leetcode例题+解析)python一级目录例题+解析三级目录一级目录例题+解析斐波那契数class Solution: def fib(self, N: int) -> int: for i in range(N+1): if i == 0: res = 0 pre2 = 0 elif i == 1:...
一级目录
例题+解析
class Solution:
def fib(self, N: int) -> int:
for i in range(N+1):
if i == 0:
res = 0
pre2 = 0
elif i == 1:
res = 1
pre1 = 1
else:
res = pre1+pre2
pre1, pre2 = res, pre1
return res
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = {}
dp[0] = 0
for i in range(1,amount+1):
dp[i] = amount+1
for coin in coins:
if i - coin < 0:
continue
dp[i] = min(dp[i], 1+dp[i-coin])
if dp[amount] == amount + 1:
return -1
else: return dp[amount]
class Solution:
def lengthOfLIS(self, nums: List[int]) -> int:
dp = {}
for i in range(len(nums)):
if i == 0:
dp[i] = 1
else:
dp[i] = 1
for j in range(i):
if nums[j] < nums[i]:
dp[i] = max(dp[i],dp[j]+1)
res = 0
for i in range(len(nums)):
res = max(res,dp[i])
return res
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
dp = {}
for i in range(len(nums)):
if i == 0:
dp[i] = nums[i]
else:
dp[i] = max(nums[i], dp[i-1]+nums[i])
res = -float('inf')
for i in range(len(nums)):
if dp[i] > res:
res = dp[i]
return res
-
背包问题(该题leetcode没有原题,但是有一些变形的题目)
class Solution:
def canPartition(self, nums: List[int]) -> bool:
sum_all = sum(nums)
if sum_all%2 != 0:
return False
sum_all = sum_all/2
dp = [[False] * int(sum_all+1) for _ in range(len(nums)+1)]
for i in range(len(nums)+1):
dp[i][0]=True
for i in range(1, len(nums)+1):
for j in range(1,int(sum_all)+1):
if nums[i-1] > j:
dp[i][j] = dp[i-1][j]
continue
if j == nums[i-1]:
dp[i][j] = True
else:
dp[i][j] = dp[i-1][j] or dp[i-1][j-nums[i-1]]
return dp[-1][-1]
压缩
class Solution:
def canPartition(self, nums: List[int]) -> bool:
sum_all = sum(nums)
if sum_all%2 != 0:
return False
sum_all = sum_all/2
dp = [False for _ in range(int(sum_all) + 1)]
dp[0] = True
for i in range(1, len(nums) + 1):
for j in range(int(sum_all), 0,-1):
if nums[i - 1] > j:
dp[j] = dp[j]
continue
if j == nums[i - 1]:
dp[j] = True
else:
dp[j] = dp[j] or dp[j - nums[i - 1]]
return dp[-1]
三级目录
本文地址:https://blog.csdn.net/weixin_43494312/article/details/107159626
上一篇: 《ASP.NET5》无法路由到Web API Controller控制器
下一篇: UnicodeDecodeError: ‘ascii‘ codec can‘t decode byte 0xcb in position 260: ordinal not in range(128)
推荐阅读
-
动态规划详解(leetcode例题+解析)python
-
LeetCode 300. 最长上升子序列(Python、动态规划、贪心算法)
-
leetcode解码方法(动态规划python)
-
leetcode 91 解码方法 (动态规划,python)
-
Python图像处理之gif动态图的解析与合成操作详解
-
Java/Python实现 LeetCode剑指Offer 14-I.剪绳子(动态规划)
-
python动态规划算法实例详解
-
动态规划(Dynamic Programming)例题步骤详解
-
动态规划详解(leetcode例题+解析)python
-
LeetCode44. 通配符匹配(python,动态规划) 通用解法