[LeetCode] Unique Paths

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   strong   io   for   

A robot is located at the top-left corner of a m x n grid (marked ‘Start‘ in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish‘ in the diagram below).

How many possible unique paths are there?

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

以下方法,用stack可以遍曆每條路徑,結果正確,但是Time Limit Exceeded!因為只要得到路徑的個數所以並不需要遍曆每條路徑!思考簡單的方法.

class Solution {public:    int uniquePaths(int m, int n) {        int row=0,col=0,res=0;        pair<int,int> rowCol;        rowCol = make_pair(row,col);        stack<pair<int,int>> stackRowCol;        stackRowCol.push(rowCol);        while(!stackRowCol.empty()){           pair<int,int> temp = stackRowCol.top();           stackRowCol.pop();           row = temp.first;           col = temp.second;           if(row==m-1 && col==n-1){              res++;              continue;}           if(row<m-1)           {               rowCol = make_pair(row+1,col);               stackRowCol.push(rowCol);           }           if(col<n-1)           {              rowCol = make_pair(row,col+1);              stackRowCol.push(rowCol);           }           }//end while        return res;    }};

用動態規劃的方法(DP),定義一個m*n大小的矩陣,矩陣裡的值表示從當前點到右下角的路徑數,假如(i,j)點到終點的路徑數是C(i,j),則

C(i,j) = C(i+1,j)+C(i,j+1);由此可以用O(m*n)的時間複雜度和O(m*n)的空間複雜度計算出結果,具體編程如下:

class Solution {public:    int uniquePaths(int m, int n) {        int row=m-2,col=n-2,res=0;        vector<int> vec0(n,1);        vector<vector<int> > vec(m,vec0);        for(int i=row;i>=0;i--){            for(int j=col;j>=0;j--){               vec[i][j]=vec[i][j+1]+vec[i+1][j];            }        }                     return vec[0][0];    }};

聯繫我們

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