[LeetCode] Unique Paths

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];
    }
};
posted @ 2014-07-25 10:41  Xylophone  Views(132)  Comments(0Edit  收藏  举报