Overlapping subproblem
보통 문제를 풀 때 완전탐색으로 먼저 접근
1 step 또는 2 steps만 올라올 수 있으니까 subproblem으로 나누면
1층 아래에서 온 값과 + 1층까지 온 최소 값
2층 아래에서 온 값과 + 2층까지 온 최소 값
이 둘 중 더 작은 값을 가져오면 된다.
var minCostClimbingStairs = function(cost) {
const memo = {};
const length = cost.length;
const dp = (n) => {
if(n===0 || n===1) return 0;
if(!(n in memo)){
memo[n] = Math.min(dp(n-1)+cost[n-1],dp(n-2)+cost[n-2]);
}
return memo[n]
}
return dp(length);
};
var minCostClimbingStairs = function(cost) {
const length = cost.length;
const dp = Array(length+1).fill(0);
// dp의 길이가 0이나 1인 경우에는 0 반환필요
for(let i=2;i<length+1;i++){
dp[i] = Math.min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2])
}
return dp[length]
};
};