Skip to content

Commit 0ca7cd8

Browse files
committed
动态规划
1 parent 897f97c commit 0ca7cd8

File tree

4 files changed

+52
-24
lines changed

4 files changed

+52
-24
lines changed

README.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -274,6 +274,12 @@ Symbol
274274

275275
[递归算法题](https://github.com/fltenwall/JavaScript_Everything/blob/main/notes/算法/递归算法题.md)
276276

277+
[动态规划](https://github.com/fltenwall/JavaScript_Everything/blob/main/notes/算法/动态规划.md)
278+
279+
贪心算法
280+
281+
分治/回溯
282+
277283

278284
#### 前端框架中的算法
279285

notes/JavaScript/test.js

Lines changed: 6 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,9 @@
1-
const fn = function(count, start, res){
2-
const mid = Math.ceil(count / 2)
3-
let index = start
4-
let arrCount = 0
5-
let tempArr = []
6-
while(index <= mid && arrCount < count){
7-
tempArr.push(index)
8-
arrCount += index
9-
if(arrCount === count){
10-
res.push(tempArr)
11-
break
12-
}
13-
++index
1+
const fibonacci = function(count){
2+
const dp = [1,1]
3+
for (let index = 2; index < count; index++) {
4+
dp[index] = dp[index-2] + dp[index-1]
145
}
15-
if(start <= mid) return fn(count, start+1, res)
6+
return dp[count-1]
167
}
178

18-
const func = function(count){
19-
let res = []
20-
fn(count, 1, res)
21-
return res
22-
}
23-
console.log(func(4)) // []
24-
console.log(func(5)) // [ [ 2, 3 ] ]
25-
console.log(func(10)) // [ [ 1, 2, 3, 4 ] ]
26-
console.log(func(15)) // [ [ 1, 2, 3, 4, 5 ], [ 4, 5, 6 ], [ 7, 8 ] ]
9+
console.log(fibonacci(10))

notes/算法/动态规划.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
2+
#### 核心思想
3+
4+
将问题划分为若干个子问题,在子问题计算的基础上,逐步构建出原问题的解
5+
6+
#### 步骤:
7+
8+
1. 定义状态
9+
10+
将原问题划分为多个子问题,定义状态表示为子问题的解,通常使用一个数组或矩阵来表示
11+
12+
2. 确定状态转移方程
13+
14+
表示从一个状态转移到另外一个状态时的转移规则。如`dp[i] = dp[i-2] + dp[i-1]`
15+
16+
3. 定义初始化状态
17+
18+
通过都是写在 for/while 循环中的
19+
20+
4. 计算原问题的解
21+
22+
通过计算状态之间的转移,得到最终问题的解。通常使用递归或循环计算。
23+
24+
#### 用动态规划求解斐波那契数列
25+
26+
```javascript
27+
const fibonacci = function(count){
28+
const dp = [1,1]
29+
for (let index = 2; index < count; index++) {
30+
dp[index] = dp[index-2] + dp[index-1]
31+
}
32+
return dp[count-1]
33+
}
34+
```
35+
36+
1. 定义状态: `dp[index]`就是i位置对应的状态(值)
37+
2. 确定状态转移方程: `dp[index] = dp[index-2] + dp[index-1]`
38+
3. 定义初始化状态: `dp = [1,1]`
39+
4. 计算原问题的解: `dp[count-1]`

notes/算法/递归算法题.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const fibonacci = function(count){
1515
}
1616
```
1717

18-
加入缓存,避免递归
18+
动态规划
1919

2020
```javascript
2121
const fibonacci = function(count){

0 commit comments

Comments
 (0)