LeetCode OJ 之 Unique Paths (不同路径)
来源:互联网 发布:java文件加密 编辑:程序博客网 时间:2024/06/16 00:06
题目:
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?
一个机器人位于一个m x n 的格子的左上端,这个机器人每次只能向下或者向右移动一步。这个机器人尝试到达格子的右下端,请问有多少种不同的路径?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
思路:
1、动态规划法
设状态 f[i][j]表示从起点(1 , 1)到达 ( i, j ) 的路线条数,则状态转移方程为:
f[i][j]=f[i-1][j]+f[i][j-1]
代码:
class Solution {public: //动态规划法,状态转移方程为f[i][j] = f[i][j-1] + f[i-1][j] int uniquePaths(int m, int n) { if(m < 1 || n < 1) return 0; //定义二维数组f[m][n] vector<vector<int> > f(m , vector<int>(n , 0)); //初始化第一行 for(int i = 0 ; i < n ; i++) { f[0][i] = 1; } //初始化第一列 for(int j = 0 ; j < m ; j++) { f[j][0] = 1; } //求状态转移结果,按行求 for(int i = 1 ; i < m ; i++) { for(int j = 1 ; j < n ; j++) { f[i][j] = f[i][j-1] + f[i-1][j]; } } return f[m-1][n-1]; }};
2、优化动态规划法的空间复杂度。用一维数组代替二维数组。
class Solution {public: //动态规划法,状态转移方程为f[i][j] = f[i][j-1] + f[i-1][j] int uniquePaths(int m, int n) { if(m < 1 || n < 1) return 0; vector<int> f(n , 0); f[0] = 1; //按行求 for(int i = 0 ; i < m ; i++) { //根据上一行保存的f 求当前行的f,当前行的f[j] 等于在上一行保存的f[j]的基础上再加上当前行的前一个,即f[j-1] //即下式中左边的 f[j] ,表示当前行的 f[j] ,与公式中的 f[i[[j] 对应 //右边的 f[j] ,表示上一行保存的的 f[j] ,与公式中的 f[i-1][j] 对应 //而f[j-1] 为当前行的f[j-1],之前已经求出 for(int j = 1 ; j < n ; j++) { f[j] = f[j] + f[j-1]; } } return f[n-1]; }};
3、DFS
class Solution {public: // 深搜,小集合可以过,大集合会超时 // 时间复杂度 O(n^4) ,空间复杂度 O(n) int uniquePaths(int m, int n) { if(m < 1 || n < 1) return 0; if(m == 1 && n ==1) return 1; return uniquePaths(m-1,n) + uniquePaths(m,n-1); }};
0 0
- LeetCode OJ 之 Unique Paths (不同路径)
- LeetCode OJ 之 Unique Paths II(不同路径 - 二)
- LeetCode OJ:Unique Paths
- LeetCode OJ Unique Paths
- LeetCode | Unique Paths(唯一路径)
- LeetCode OJ:Unique Paths II
- LeetCode OJ - Unique Paths II
- LeetCode OJ Unique Paths II
- leetcode oj java Unique Paths
- LeetCode OJ 62. Unique Paths
- LeetCode OJ 之 Binary Tree Paths(二叉树路径)
- LeetCode 之 Unique Paths
- leetcode 之 Unique Paths
- leetcode 之Unique Paths
- Leetcode 之 Unique Paths
- LeetCode之Unique Paths
- leetcode之Unique Paths
- leetcode之Unique Paths
- 数组双指针法汇总
- 安装MySQL-python方法与错误解法
- MapReuce 算法设计(一)---Combiner 和 In-Mapper Combing
- JDK8 十大新特性
- 【总结帖】技术路线及书单
- LeetCode OJ 之 Unique Paths (不同路径)
- 第十六周项目3 用指针调用函数
- 逃离迷宫
- 使用OPENSSH连接越狱后的iphone实…
- linux学习笔记-硬件篇
- Linux中文档权限说明
- Azure架设Discuz论坛笔记
- centos文件详解
- MapReduce 算法设计(二)--- Pairs 和 Stripes