Comments (2)
动态规划其实是分治策略的一个子集,即将一个原问题分解为若干个规模较小的子问题,递归的求解这些子问题,然后合并子问题的解得到原问题的解。 关键点就在于这些子问题会有重叠,一个子问题在求解后,可能会再次求解多次,解决思路是将已求解的子问题的解存储起来,当下次再次求解这个子问题时,直接套用即可。
分治策略一般用来解决子问题相互对立的问题,称为标准分治,而动态规划用来解决子问题重叠的问题。
动态规划概念的关键点:
- 动态规划法只会解决每个子问题一次
- 一旦某个给定子问题的解已经算出,则将其记忆化存储,以便下次需要同一个子问题解之时直接查用
继续以上爬台阶问题,从 f(n)->...->f(n-k)+f(n-k-1)->...->f(2) + F(1),会存在重复计算 f(n-k)、f(n-k-1)
的问题。
用动态规划的思路,可以将问题解决办法倒转一下,即从递归出口向上推导:
第一次迭代,如果台阶数为 3 ,那么走法数为 3 ,通过 f(3) = f(2) + f(1) 得来。
第二次迭代,如果台阶数为 4 ,那么走法数为 5 ,通过 f(4) = f(3) + f(2) 得来。
// 第 n-k 次 ...
由此可见,每一次迭代过程中,只需要保留之前的两个状态,就可以推到出新的状态。翻译成代码如下:
/**
* @param {number} n
* @return {number}
*/
var climbStairs = function(n) {
const dp = [];
dp[1] = 1;
dp[2] = 2;
for(let i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
};
复杂度分析:
时间复杂度:O(n),单循环到 n
空间复杂度:O(n),dp 数组用了 n 的空间。
from blog.
TODOS:
- 树形DP:01背包问题
- 线性DP:最长公共子序列、最长公共子串
- 区间DP:矩阵最大值(和以及积)
- 数位DP:数字游戏
- 状态压缩DP:旅行商
from blog.
Related Issues (20)
- 前端工程化相关 HOT 5
- Node.js 学习笔记 HOT 1
- Apollo GraphQL
- 二叉树 HOT 1
- 深入理解 async/await HOT 1
- 浏览器渲染及性能优化 HOT 4
- 实现 new 操作符 HOT 2
- 图论算法
- 搜索与回溯算法
- 从零扒一扒 promise HOT 1
- Java 学习笔记 HOT 5
- Eslint 插件
- A Recap of Frontend Development in 2019
- 关于编译和执行 HOT 2
- Js bridge & React Native通信机制
- 小程序
- 深入理解现代浏览器架构(part 1)
- 深入理解现代浏览器架构(part 2)
- 深入理解现代浏览器架构(part 3)
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from blog.