[leetcode] 45. 跳躍遊戲 II(Java)(動態規劃)

來源:互聯網
上載者:User

標籤:樣本   .com   com   class   使用   value   problem   條件   math   

45. 跳躍遊戲 II

動態規劃
此題可以倒著想。
看樣本:
[2,3,1,1,4]
我們從後往前推,對於第4個數1,跳一次
對於第3個數1,顯然只能跳到第4個數上,那麼從第3個數開始跳到最後需要兩次
對於第2個數3,顯然一步到位,跳一次
對於第一個數2,只能選擇跳一次還是跳兩次,顯然選擇跳一次的收益更大,最終只需跳兩次

倒著推時發現滿足①最優子結構,②重疊子問題。可以使用動態規劃。

狀態原因:f[i]表示在第i個位置最小需要幾次可跳到最後一個位置
狀態轉移方程:f[i] = min(f[i+1]~f[nums[i]])+1
初始條件f[nums.length()-1]=0

class Solution {    public int jump(int[] nums) {        int f[] = new int[nums.length];        if (nums.length == 0) {            return 0;        }        if (nums.length == 1) {            return 0;        }        f[nums.length - 1] = 0;        for (int i = nums.length - 2; i >= 0; i--) {            f[i] = findMin(f, i, nums[i]) + 1;            if (f[i] < 0) f[i] = Integer.MAX_VALUE;        }        return f[0];    }    private int findMin(int[] f, int i, int num) {        int min = Integer.MAX_VALUE;        for (int j = 1; j <= num && i + j < f.length; j++) {            min = Math.min(min, f[i + j]);        }        return min;    }}

[leetcode] 45. 跳躍遊戲 II(Java)(動態規劃)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.