# 动态规划

## 分析解答

``````dynFib(n) {
let arr = new Array(n).fill(0);
arr[0] = 1;
arr[1] = 1;
for (let i = 2; i < n; i++) {
arr[i] = arr[i - 1] + arr[i - 2];
}
// 返回最后一个
return arr[n - 1];
}``````

``````const product = [
{ weight: 2, value: 3},
{ weight: 2, value: 6 },
{ weight: 6, value: 5 },
{ weight: 5, value: 4 },
{ weight: 4, value: 6 },
];``````

......

``````this.result = [];

const row = this.product.length;
const col = this.capacity;
for (let i = 0; i < row; i++) {
this.result[i] = new Array(col + 1).fill(0);
}``````

``this.result[-1] = new Array(col + 1).fill(0);``

``````calculate() {
const row = this.product.length;
const col = this.capacity;
let product;
for (let i = 0; i < row; i++) {
for (let j = 0; j < col + 1; j++) {
product = this.product[i];
if (j < product.weight) {
this.result[i][j] = this.result[i - 1][j];
} else {
this.result[i][j] = Math.max(
this.result[i - 1][j],
this.result[i - 1][j - product.weight] + product.value
);
}
}
}
delete this.result[-1];
return this.result[row - 1][col];
}``````

• 拆分、划分问题到某个颗度时，我们可以很轻易的做出决策
• 确定状态方程，比如上面的: fi= Math.max(fi-1,fi-1-c[i]]+w[i])

709 声望
145 粉丝
0 条评论