标签:leetcode
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.
机器人只能向右走和向下走,那么我们可以很容易想到,到一个点的路径数,是不是等于到这个点的左边的点的路径数,加上到达这个点的上边的点的路径数。
接下来考虑特殊情况,第一列的点,左边没有其他点,所以只能通过它上方的点到达。第一行的点,只能通过它左边的点到达,再想一下,第一行的点的路径数是不是只能为 1?
看到这里,你是不是想用二维数组?其实没有必要,因为我们不需要那么多状态的记录。我们仅仅需要的是上一次迭代的结果(也就是上一行)。假如我用一个长度为 n 的一维数组保存到达一行的点的路径数的话,那么用 m-1 次迭代(为什么用 m - 1?),每次迭代时数组一开始保存的就是上一行的计算结果,这时候我只要让这个点加等于它左边的点的路径数,就得到该点的结果了。
C++:
class Solution {
public:
int uniquePaths(int m, int n) {
int* dp = new int[n];
for(int i = 0;i < n;++i)
dp[i] = 1;
for(int i = 1;i < m;++i)
{
for(int j = 1;j < n;++j)
{
dp[j] += dp[j-1];
}
}
int ans = dp[n-1];
delete []dp;
return ans;
}
};
Python:
class Solution:
# @param {integer} m
# @param {integer} n
# @return {integer}
def uniquePaths(self, m, n):
dp = [1 for i in range(0,n)]
for i in range(1,m):
for j in range(1,n):
dp[j] = dp[j] + dp[j-1]
return dp[n-1]标签:leetcode
原文地址:http://blog.csdn.net/jcjc918/article/details/44513437