【LeetCode】62. Unique Paths解法及注释
来源:互联网 发布:邯郸市网络教研 编辑:程序博客网 时间:2024/05/18 00:41
62. 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-1+n-1)步,向右行进和向下行进的步数是确定的,只是一个顺序问题,本质上就是一个高中数学里的排列组合问题:总共有(m+n-2)个位置,将向右行进的(n-1)个位置插入其中(或者将向下行进的(m-1)个位置插入其中):
但是按照这个数学算式求解复杂度比较高,特别是题目规定 0=<m,n<=100,这样需要做多次乘法,效率不高。
针对本题,更合适的方法是“动态规划”方法:欲到达终点position[m][n],必先达到position[m-1][n]或者position[m][n-1],如是,到达position[m-1][n]和position[m][n-1]的路径数之和就是到达position[m][n]的路径总数,我们可通过两重循环解决问题:
【解法及注释】
class Solution {public: int uniquePaths(int m, int n) { vector<vector<int>> path(m, vector<int>(n, 1));//初始化路径矩阵中的每一格为1,相当于行进步长 for(int i=1; i<m; i++)//初始位置为path[0][0],故循环起始为1 { for(int j=1; j<n; j++) { path[i][j] = path[i-1][j] + path[i][j-1]; } } return path[m-1][n-1]; }};
- 【LeetCode】62. Unique Paths解法及注释
- Unique Paths问题及解法
- 【LeetCode】96. Unique Binary Search Trees 解法及注释
- Unique Paths II问题及解法
- [LeetCode]62.Unique Paths
- LeetCode --- 62. Unique Paths
- LeetCode 62.Unique Paths
- [Leetcode] 62. Unique Paths
- [leetcode] 62.Unique Paths
- [leetcode] 62.Unique Paths
- leetcode 62. Unique Paths
- Leetcode 62. Unique Paths
- [leetcode] 62. Unique Paths
- 62. Unique Paths LeetCode
- [LeetCode]62. Unique Paths
- 【LeetCOde】62. Unique Paths
- [LeetCode]62. Unique Paths
- leetcode 62. Unique Paths
- linux lcd设备驱动剖析二
- OpenCV 图像几何变换:旋转,缩放,斜切
- Linux远程管理器xshell和xftp使用教程
- 【笔记】 《js权威指南》- 第16章 脚本化CSS 16.1 CSS概览
- C++第三次实验
- 【LeetCode】62. Unique Paths解法及注释
- C++实验3
- 【AC自动机】【数据结构】【树】【Aho-Corasick automation】AC自动机理解(入门)
- CGAL VS2010环境变量
- android中TextView分段展示不同颜色,字体,时间
- Java中Synchronized的用法
- C++第三次试验2.1
- 关于表单提交数据转Json
- Mapper抽象类参数