Unique Paths

来源:互联网 发布:大数据下的机械工程 编辑:程序博客网 时间:2024/05/01 21:24

题目:

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).

Note: m and n will be at most 100.

分析:仔细观察可以发现,第m行n列中的步数等于第m-1行n列中的步数和m行n-1列中的步数之和。

代码如下:

int uniquePaths(int m, int n) {

        if(m==0||n==0)return 0;
        if(m==1||n==1)return 1;
        int **matrix=new int *[m];
        for(int i=0;i<m;i++)
        {
            matrix[i]=new int[n];
        }
        for(int i=0;i<m;i++)
        {
            matrix[i][0]=1;
        }
        for(int i=1;i<n;i++)
        {
            matrix[0][i]=1;
        }
        for(int i=1;i<m;i++)
        {
           for(int j=1;j<n;j++)
           {
               matrix[i][j]=matrix[i][j-1]+matrix[i-1][j];
           }
        }
        int result = matrix[m-1][n-1];
        for(int i=0;i<m;i++)
        {
            delete []matrix[i];
        }
        delete []matrix;
        return result;
    }
原创粉丝点击