Unique Paths
2015-07-13 10:05
471 查看
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?
![](http://img.blog.csdn.net/20150713095450988)
Above is a 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
思路:robot要么向下走,要么向下走,求总共的次数,就应该是向右走之后和向下走之后的次数的总和,这个问题和青蛙跳台阶很类似,可以转化为递归,但是递归超时了,一样的,同青蛙跳台阶一样,将递归转化为迭代。
迭代: 可以把机器人当作终点,星星当作起点,a[i][j]表示的是第i行和第j列时到终点的总的路径数,那么就有a[i][j] = a[i - 1][j] + a[i][j - 1];
初始化条件 ,最后a[m-1][n-1]的值即为所求。
a[i][0] = 1; i从1到n-1
a[0][j] = 1; j 从1到m-1
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.
思路:robot要么向下走,要么向下走,求总共的次数,就应该是向右走之后和向下走之后的次数的总和,这个问题和青蛙跳台阶很类似,可以转化为递归,但是递归超时了,一样的,同青蛙跳台阶一样,将递归转化为迭代。
public int uniquePaths(int m, int n) { if (m <= 0 || n <= 0) return 0; return paths(m, n, 1, 1); } public int paths(int m, int n, int right, int down) { if (right == n && down < m) return 1; if (right < n && down == m) return 1; return paths(m, n, right + 1, down) + paths(m, n, right, down + 1); }
迭代: 可以把机器人当作终点,星星当作起点,a[i][j]表示的是第i行和第j列时到终点的总的路径数,那么就有a[i][j] = a[i - 1][j] + a[i][j - 1];
初始化条件 ,最后a[m-1][n-1]的值即为所求。
a[i][0] = 1; i从1到n-1
a[0][j] = 1; j 从1到m-1
public class Solution { public int uniquePaths(int m, int n) { if (m <= 0 || n <= 0) return 0; if(m==1||n==1) return 1; int[][] a = new int[m] ; a[0][0] = 0; for (int i = 1; i <= m - 1; i++) a[i][0] = 1; for (int j = 1; j <= n - 1; j++) a[0][j] = 1; for (int i = 1; i <= m - 1; i++) { for (int j = 1; j <= n - 1; j++) { a[i][j] = a[i - 1][j] + a[i][j - 1]; } } return a[m - 1][n - 1]; } }
相关文章推荐
- HDU 1503 Advanced Fruits (LCS,变形)
- iOS开发UI篇 -- UITableView
- VS 2013使用SOUI时(vcpkgsrv.exe)进程导致物理内存升高解决的办法
- [Leetcode 232, Easy] Implement Queue using Stacks
- QWidget: Cannot create a QWidget when no GUI is being used
- 自定义uitableviewcell,层层封装
- UIImageView学习记录
- UIDatePicker学习记录
- [LeetCode]N-Queens II
- Qt Quick之StackView详解(1)
- 开始刷leetcode day63:Implement Queue using Stacks
- UVALive - 4643 Twenty Questions (状态压缩)
- Quick Reference Guide for Intel® Core™ Processor Graphics
- 打开FlashBuilder秒退
- 实时获取UITextField内容
- UIKit框架-04.UIButton
- UIKit框架 - 03.UIImageView
- UIKit框架 -02.UILabel
- UIKit框架-01.UIView
- 设计模式(4) - Builder模式