leetcode第一刷_Jump Game II

來源:互聯網
上載者:User

要求最小的步數,是不是很容易想到用dp啊?

我一開始的做法是,當找到了一個可以從它延伸到更遠的位置,就把這個位置和最遠位置的步數都更新一下,結果逾時了。其實這樣不僅是逾時的,而且是錯誤的。因為這段距離裡的很多點,其實是上一步就能到達的。其實應該更新的只有哪些新的能夠到達的點,那哪些點是新的能到達的點呢?假設這次能夠延伸更遠的點是i,它的前進步數是A[i],上一次能夠到達的最遠的點是mmax,那新的能到達的點應該是(mmax, i+A[i] ]這個之間的這些位置。時間複雜度一下子變成線性了。

class Solution {public:    int jump(int A[], int n) {        if(n <= 1)  return 0;        vector<int> steps(n, INT_MAX);        steps[0] = 0;        int mmax=0;        for(int i=0;i<n-1;i++){            if(i+A[i]>mmax){                for(int j=mmax+1;j<=i+A[i]&&j<n;j++)                    steps[j] = steps[i]+1;                if(i+A[i]>=n-1)                    steps[n-1] = min(steps[n-1], steps[i]+1);                mmax = i+A[i];            }        }        return steps[n-1];    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.