LeetCode题库解答与分析——#62. 不同路径UniquePaths
2018-03-17 16:20
666 查看
#62 不同路径 Unique Paths
机器人位于一个 m x n 网格的左上角, 在下图中标记为“Start” (开始)。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角,在下图中标记为“Finish”(结束)。
问有多少条不同的路径?
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?
例如,上图是一个3 x 7网格。有多少可能的路径?注意: m 和 n 的值均不超过 100。个人思路:
把每一步当做最后一步,计算到达当前格子可以有多少种路径。其中第一格只有一种路径,即为1。很容易可以推断,由于只能向右或向下走,第一行和第一列均只有一种路径可以到达。通过将左边和上方格子的路径数相加,逐个计算每个格的路径数,可得到最后一个格的路径数。
代码(JavaScript):/**
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function(m, n) {
var row=0,col=0;
var r=Math.min(m,n);
var c=Math.max(m,n);
var ways=Array(c);
for(var i=0;i<c;i++){
ways[i]=1;
}
for(row=1;row<r;row++){
for(col=1;col<c;col++){
ways[col]+=ways[col-1];
}
}
return ways[c-1];
};
机器人位于一个 m x n 网格的左上角, 在下图中标记为“Start” (开始)。
机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角,在下图中标记为“Finish”(结束)。
问有多少条不同的路径?
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?
例如,上图是一个3 x 7网格。有多少可能的路径?注意: m 和 n 的值均不超过 100。个人思路:
把每一步当做最后一步,计算到达当前格子可以有多少种路径。其中第一格只有一种路径,即为1。很容易可以推断,由于只能向右或向下走,第一行和第一列均只有一种路径可以到达。通过将左边和上方格子的路径数相加,逐个计算每个格的路径数,可得到最后一个格的路径数。
代码(JavaScript):/**
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function(m, n) {
var row=0,col=0;
var r=Math.min(m,n);
var c=Math.max(m,n);
var ways=Array(c);
for(var i=0;i<c;i++){
ways[i]=1;
}
for(row=1;row<r;row++){
for(col=1;col<c;col++){
ways[col]+=ways[col-1];
}
}
return ways[c-1];
};
相关文章推荐
- LeetCode题库解答与分析——#63.不同路径IIUniquePathsII
- LeetCode题库解答与分析——#95. 不同的二叉查找树 IIUniqueBinarySearchTreeII
- LeetCode题库解答与分析——#96. 不同的二叉查找树UniqueBinarySearchTree
- LeetCode题库解答与分析——#120. 三角形最小路径和Triangle
- LeetCode题库解答与分析——#152. 乘积最大子序列MaximumProductSubarray
- LeetCode题库解答与分析——#5.最长回文子串LongestPalindromicSubstring
- LeetCode题库解答与分析——#1.两数之和TwoSum
- LeetCode题库解答与分析——#12.整数转罗马数字IntegerToRoman
- LeetCode题库解答与分析——#9.回文数PalindromeNumber
- LeetCode题库解答与分析——#53.最大子序和MaximumSubarray
- LeetCode题库解答与分析——#2.两数相加AddTwoNumbers
- LeetCode题库解答与分析——#70. 爬楼梯ClimbingStairs
- LeetCode题库解答与分析——#121. 买卖股票的最佳时机BestTimeToBuyAndSellStock
- LeetCode题库解答与分析——#7.颠倒整数ReverseInteger
- LeetCode题库解答与分析——#3.无重复字符的最长子串LongestSubstringWithoutRepeatingCharacters
- LeetCode --- 62. 不同路径
- LeetCode题库解答与分析——#91. 解码方法DecodeWays
- 【LeetCode题意分析&解答】39. Combination Sum
- 实时路况分析:不同路段车速预测、推荐(距离、时间、路况)最优路径
- LeetCode 63. Unique Path II(所有不同路径之二)