leecode 解题总结:62. Unique Paths
来源:互联网 发布:微信一键传图软件 编辑:程序博客网 时间:2024/06/03 18:22
#include <iostream>#include <stdio.h>#include <vector>using namespace std;/*问题: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.分析:程序员面试金典的一道题目。这是递归。可以从后向前分析最后的位置可能是从左边或者上边过来的。设dp[i][j]表示到达位置(i,j)的无重复路径个数,dp[i][j] = dp[i-1][j] + dp[i][j-1]其中dp[i][0] = 1,dp[0][j]=1目标求dp[m-1][n-1]输入:2(行数) 2(列数)1 11 33 13 23 3输出:211136关键:1 既然是dp,可以直接迭代来做,不需要递归*/class Solution {public:int dfs( vector< vector<int> >& paths , int row , int col ){if(paths.empty() || row < 0 || col < 0){return 0;}//如果当前位置求得值,直接返回if(paths.at(row).at(col) != 0){return paths.at(row).at(col);}//没有求出位置,利用状态迁移方程计算else{paths.at(row).at(col) = dfs(paths , row - 1 , col) + dfs(paths , row , col - 1);return paths.at(row).at(col);}} int uniquePaths(int m, int n) {//参数检查if(m <= 0 || n <= 0){return 0;}//初始化边界值为1vector< vector<int> > paths( m , vector<int>(n , 1) );//动态规划查找//int result = dfs(paths , m - 1 , n - 1);//动态规划直接地推,无需递归for(int i = 1; i < m ; i++){for(int j = 1 ; j < n ; j++){paths[i][j] = paths[i-1][j] + paths[i][j-1];}}return paths.at(m-1).at(n-1); }};void process(){ Solution solution; int row; int col; while(cin >> row >> col ) { int result = solution.uniquePaths(row , col); cout << result << endl; }}int main(int argc , char* argv[]){process();getchar();return 0;}
0 0
- leecode 解题总结:62. Unique Paths
- leecode 解题总结:63. Unique Paths II
- leecode 解题总结:95. Unique Binary Search Trees II
- leecode 解题总结:96. Unique Binary Search Trees
- leecode 解题总结:357. Count Numbers with Unique Digits
- [leetcode] 62. Unique Paths 解题报告
- leetcode解题报告:62. Unique Paths
- [Leetcode] 62. Unique Paths 解题报告
- 【LeetCode】62.Unique Paths解题报告
- 【LeetCode】Unique Paths 解题报告
- [LeetCode] Unique Paths 解题报告
- unique-paths 总结
- Leetcode #62. Unique Paths 路径搜寻 解题报告
- Leetcode解题笔记 62. Unique Paths [Medium] 动态规划
- leecode 解题总结:46. Permutations
- leecode 解题总结:77. Combinations
- leecode 解题总结:78. Subsets
- leecode 解题总结:120. Triangle
- 谁拿了最多奖学金
- 如何将List<Interger> 转为List<String>
- 如何优雅地 对深度神经网络 进行训练
- 网站开发进阶(四十五)浅谈XML与HTML的区别
- 最大流EK算法模板
- leecode 解题总结:62. Unique Paths
- redhat虚拟机
- PAT甲级练习1010. Radix (25)
- cocos2dx-js(3.14版本) JS与C++ 互调 JS与JAVA 互调,JS与OC 互调
- leetcode -- 101. Symmetric Tree 【对称树,结构,内容】
- 自定义圆继承button实现多点触控和单点触控
- 深入理解JVM(八)——类加载的时机
- OpenCV画椭圆、实心圆、凹多边形、线段、矩形
- Mybatis中使用占位符#