题解 | #最小花费爬楼梯#
最小花费爬楼梯
https://www.nowcoder.com/practice/9b969a3ec20149e3b870b256ad40844e
let buf = '' process.stdin.on('readable', () => { let chunk = process.stdin.read() if (chunk) buf += chunk.toString() }) let n let cost = [] let dp = [] process.stdin.on('end', () => { buf.split('\n').forEach((line, i) => { if (i === 0) n = Number(line) else if (i === 1) cost = line.split(' ').map(Number) else { dp[0] = 0 dp[1] = 0 for (let s = 2; s <= n; s++) { dp[s] = Math.min(dp[s - 1] + +cost[s - 1], dp[s - 2] + cost[s - 2]) } console.log(dp[n]) } }) })
解析
dp[x]代表第x台阶的已花费,状态转移方程:dp[x] = Math.min(dp[x - 1] + cost[x - 1], dp[x - 2] + cost[x - 2])
说明:dp[x - 1]一步之前的花费,cost[x - 1]如果真的走了这个台阶的花费
第一次自己做出dp好激动