题目:http://oj.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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
题目翻译:
机器人位于m x n网格的左上角(标有'Start')。
在任何时间,机器人只能向下或向右移动。机器人试图到达网格的右下角(标有'Finish')。
有多少种可能的不同路径?
注意:m和n最大为100。
分析:
使用二维数组来实现。规律为除了第一行和第一列全为1外,其他格的路径数为其上一格和左一格的和。
C++实现:
<span style="font-size:14px;"> int A[m][n];
for(int i = 0; i < m; ++i)
{
A[i][0] = 1;
}
for(int i = 1; i < n; ++i)
{
A[0][i] = 1;
}
for(int i = 1; i < m; ++i)
for(int j = 1; j < n; ++j)
{
A[i][j] = A[i][j - 1] + A[i - 1][j];
}
return A[m - 1][n - 1];</span>
Java实现:
<span style="font-size:14px;">public class Solution {
public int uniquePaths(int m, int n) {
int[][] A = new int[m][n];
for (int i = 0; i < m; ++i) {
A[i][0] = 1;
}
for (int i = 1; i < n; ++i) {
A[0][i] = 1;
}
for (int i = 1; i < m; ++i)
for (int j = 1; j < n; ++j) {
A[i][j] = A[i][j - 1] + A[i - 1][j];
}
return A[m - 1][n - 1];
}
}</span>
Python实现:
<span style="font-size:14px;">class Solution:
# @return an integer
def uniquePaths(self, m, n):
paths = [[1] for i in range(m)] # initialize the 1st column to be 1
for i in range(n - 1): # initialize the 1st row to be 1
paths[0].append(1)
for i in range(m - 1):
for j in range(n - 1):
paths[i + 1].append(paths[i][j + 1] + paths[i + 1][j])
return paths[m - 1][n - 1]</span>
感谢阅读,欢迎评论!