您的位置:首页 > 产品设计 > UI/UE

Unique Paths

2015-08-19 19:00 316 查看
原题如下(链接:https://leetcode.com/problems/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?

解题思路:可以类比到青蛙跳台阶的题,其实只要找到一个递推公式就可以了,F(m,n) = F(m-1, n) + F(m, n-1);

递归求解的话会超时,但是比较容易理解,代码如下:

[code] int uniquePaths(int m, int n) {
        if(m < 1 || n < 1)
           return 0;

        if(n == 1 || m == 1)
           return 1;
        else
           return uniquePaths(m-1, n) + uniquePaths(m, n-1);
           }


把递归改成循环可以顺利AC,C++代码如下:

[code]    int uniquePaths(int m, int n) {
        if(m < 1 || n < 1)
           return 0;

        int **mn = new int*[m];
        for(int i=0; i<m; i++){
            mn[i] = new int
;
        }

        for(int i=0; i<m; i++){
            mn[i][0] = 1;
        }

        for(int i=0; i<n; i++){
            mn[0][i] = 1;
        }

        for(int i=1; i<m; i++){
            for(int j=1; j<n; j++){
                mn[i][j] = mn[i][j-1] + mn[i-1][j];
            }
        }

        return mn[m-1][n-1];  
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: