标签:mtr col result ESS 连续子序列 ide cos mic 相加
动态规划 Dynamic Programming
def coin(n): dp = [0] * (n + 1) dp[0] = dp[1] = dp[2] = 1 dp[3] = 2 for i in range(4, n + 1): dp[i] = dp[i - 1] + dp[i - 3] + dp[i - 4] return dp[n]
例二:入室抢劫
问题描述:
def rob(nums): n = len(nums) dp = [ [0] * 2 for _ in range(n + 1)] for i in range(1, n + 1): dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]) # forget it dp[i][1] = nums[i - 1] + dp[i - 1][0] # let‘s do it return max(dp[n][0], dp[n][1])
优化空间到O(1)
def rob(nums): yes, no = 0, 0 for i in nums: no, yes = max(no, yes), i + no return max(no, yes)
例三:入室抢劫Ⅱ
def rob(nums): def rob(nums): yes, no = 0, 0 for i in nums: no, yes = max(no, yes), i + no return max(no, yes) return max(rob(nums[len(nums) != 1:]), rob(nums[:-1]))
例四:组织聚会
def minCostClimbingStairs2(cost): dp0, dp1, dp2 = 0, 0, 0 for i in range(2, len(cost) + 1): dp2 = min(dp0 + cost[i - 2], dp1 + cost[i - 1]) dp0, dp1 = dp1, dp2 return dp2
另:
def numDecodings(s): if s=="" or s[0]==‘0‘: return 0 dp=[1,1] for i in range(2,len(s)+1): # if it is 0, then dp[i] = 0 result = 0 if 10 <=int(s[i-2:i]) <=26: result = dp[i-2] if s[i-1] != ‘0‘: result += dp[i-1] dp.append(result) return dp[len(s)]
例七:独特二叉树搜索路径 (卡特兰数)
def numTress(n): if n <= 2: return n sol = [0] * (n + 1) sol[0] = sol[1] = 1 for i in range(2, n + 1): for left in range (0, i): sol[i] += sol[left] * sol[i - 1 - left] return sol[n]
例八:最大子序列乘积
def maxProduct(nums): if len(nums) == 0: return 0 maximum = minimum = result = nums[0] for i in range(1, len(nums)): maximum, minimum = max(maximum * nums[i], minimum * nums[i], nums[i]), min(maximum * nums[i], minimum * nums[i], nums[i]) result = max(result, maximum) return result
标签:mtr col result ESS 连续子序列 ide cos mic 相加
原文地址:https://www.cnblogs.com/oldby/p/12829473.html