森田賢二のleetCodeの使い方、解説、解答を毎日更新しているキャラクター

[leetcode]問題解答と解説。746. Min Cost Climbing Stairs [JavaScript]

[leetcode]問題解答と解説。746. Min Cost Climbing Stairs [JavaScript]

皆さんleetCode好きですよね。私も好きです。
なかなかやる機会がないのですよね。
leetCodeの使い方や解説ではなく実際に問題を解決するために何をしたか
をメモ書きして行きます

私はある決意をして今挑んでいます。
モチベーションを保つためだけにこれをやっています。

では今日のleetCode。
【746. Min Cost Climbing Stairs】の解決策と方法。自分がまず挑戦して
やったことをさらけ出します。

※下にある自分のコードは自分で設けた制限時間内に書けたところまです。

これは
「私は年末までこれを続けたらどんなleetCoderになるか」のシリーズ。
実験的ブログ更新です。

森田賢二のleetCode
森田賢二のleetCode

[leetcode] 746. Min Cost Climbing Stairs ルール

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

You can either start from the step with index 0, or the step with index 1.

Return the minimum cost to reach the top of the floor.

exampleは実際の問題ページを見てください

[leetcode] 746. Min Cost Climbing Stairs 問題ページ

198. House Robber

[leetcode] 746. Min Cost Climbing Stairs

my code is not good(time out)

時間切れ。
でも調べながらやった
自分がわからなかったところはスワップするところ。

[leetcode] 746. Min Cost Climbing Stairs。discussの中の一つの解答例

数ある中からJavaScriptのもので、理解しやすい解説をピックアップしました。
discussから見ればさらにもっと違う方法で真似したくなるものがあるかもしれない

JavaScriptでfilterされている、discussはこちらから

気に入った解答1

var minCostClimbingStairs = function(cost) {
    if (cost.length === 1) return 0;
    if (cost.length === 2) return Math.min(cost[0], cost[1]); // 辿る必要がないため

    // これらが仕様のステップできる数
    let minCostTwoBefore = cost[0]; // 初期値
    let minCostOneBefore = cost[1];

    for (let n = 2; n < cost.length; n++) { // 既に2以下は返しているので2から始める
        const minCostAtCurrent = cost[n] + Math.min(minCostOneBefore, minCostTwoBefore); //辿ってきた積算のどちらかと現在の値をたす

        // 次の用意をしている
        minCostTwoBefore = minCostOneBefore; // 1つ前の積算結果は次では2つ前になるため
        minCostOneBefore = minCostAtCurrent;  // 今回の結果は次の1つ前になるため
    }

    return Math.min(minCostOneBefore, minCostTwoBefore);
};

これの
minCostTwoBefore = minCostOneBefore;
minCostOneBefore = minCostAtCurrent;
のぶぶんだった

他の解説では簡単に
first、secondとされているものも多く
変数名は大事で、それ次第で理解難易度がグッと下がるなと思ったね

[leetcode] 746. Min Cost Climbing Stairs をやってみて感想

  • 積算していく様子が理解できました
  • dpとしてn分の配列を作る方法もあり

カテゴリー leetCode