62. Unique Paths

来源:互联网 发布:php 数组的数组 编辑:程序博客网 时间:2024/06/11 22:07

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?

题目开始可以尝试使用简单的递归,发现超时
后来尝试使用动态规划的算法,最后p[m][n]的步数取决于前面p[m-1][n]和p[m][n-1]的大小,当m=0或者n=0时,也就是只有一行或者一列,那么前面只有一种走法。

class Solution {public:    int uniquePaths(int m, int n) {      int p[m][n];        for(int i = 0;i<m;i++) {            for(int j = 0;j<n;j++) {                if(i==0||j==0){                    p[i][j] = 1;                }                else                p[i][j] = p [i-1][j] + p[i][j-1];            }        }        return p[m-1][n-1];    }};
0 0
原创粉丝点击