【LeetCode-面試算法經典-Java實現】【062-Unique Paths(唯一路徑)】
【062-Unique Paths(唯一路徑)】
【LeetCode-面試算法經典-Java實現】【全部題目文件夾索引】
原題
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*n的方格的左上角。
機器人僅僅能向右或都向下走一個方格,機器人要到達右下角的方格。
請問一共同擁有多少種唯一的路徑。
註意:m和n最大不超100。
解題思路
典型的動態規劃問題,對問題使用動態規劃的方法進行求解。
用一個m*n的組數A保存結果。
對於A數組中的元素有。
1、當x=0或者y=0時有A[x][y] = 1;
2、當x>=1而且y>=1時有A[\x][\y] = A[x-1][y]+A[\x][y-1]。
3、所求的結點就是A[m-1][n-1]。
代碼實現
算法實現類
public class Solution {
public int uniquePaths(int m, int n) {
int[][] result = new int[m][n];
// 第一列的解
for (int i = 0; i < m; i++) {
result[i][0] = 1;
}
// 第一行的解
for (int i = 1; i < n; i++) {
result[0 ][i] = 1;
}
// 其他位置的解
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
result[i][j] = result[i - 1][j] + result[i][j - 1];
}
}
// 所求的解
return result[m - 1][n - 1];
}
}
評測結果
點擊圖片,鼠標不釋放。拖動一段位置,釋放後在新的窗體中查看完整圖片。
特別說明
歡迎轉載。轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47182719】
【LeetCode-面試算法經典-Java實現】【062-Unique Paths(唯一路徑)】