常见的动态规划问题:
很多都是数列,在看到问题的时候,想着能不能在后面加一层数据,如果加的数据之后,结果和现在的结果不同,并且有相关性,考虑用动态规划
123 买卖股票
dp[i][j]
类型的,和普通的dp[i]
一样,只不过多循环了几遍,在思考思路的时候,和普通的一样,先寻找递推公式,只不过需要多重复几遍,在实现代码的时候,在最外层多加上一层 for 循环。
DP[i][j] = max(DP[i][j - 1], prices[j] - prices[k] + DP[i - 1][k - 1](k = 0: j - 1))
1 | public int maxProfit(int[] prices) { |
优化一下:
1 | int maxProfit(vector<int> &prices) { |
讨论区最精简的写法:
1 | public int maxProfit(int[] prices) { |
理解:
斐波那契数列
爬楼梯,摆砖块
d[i]=d[i-1]+d[i-2]