动态规划(Dynamic programmer - DP)
参考链接
动态规划
斐波那契数列
状态转移方程:
1、暴力解法
function fib(n){
if (n <=1) {
return n;
}
return fib(n-1) + f(n-2)
}
2、带备忘录的递归解法 O(n)
var fib = function (n) {
if(n<=1){
return n;
}
let memo = []
if(memo[n] === undefined){
memo[m] = fib(n-1) + fib(n-2)
}
return memo[n];
};
3、DP数组的迭代解法 O(n) 自底向上
var fib = function(n){
let db = []
db[0] = 0,db[1]=1;
for(let i=2;i<=n;i++){
dp[i] = dp[i-1] + dp[i-2]
}
return dp[n];
}
4、”状态压缩“ 迭代法 O(n)
var fib = function (n) {
if (n <=1) {
return n;
}
let prev = 0,
curr = 1;
for (let i = 2; i <= n; i++) {
let sum = prev + curr;
prev = curr;
curr = sum;
}
return curr;
};
322. 零钱兑换
base case: amount = 0
状态:amount
选择: coins[]
明确DP函数定义
备忘录
// 自顶向下 - 备忘录
var coinChange = function (coins, amount) {
let memo = [];
return dp(coins, amount, memo);
};
var dp = function (coins, amount, memo) {
if (memo[amount]) {
return memo[amount];
}
if (amount == 0) {
return 0;
}
if (amount < 0) {
return -1;
}
let res = Infinity;
for (let coin of coins) {
subproblem = dp(coins, amount - coin, memo);
if (subproblem == -1) continue;
res = Math.min(res, 1 + subproblem);
}
memo[amount] = res;
return res != Infinity ? res : -1;
};