首页 技术 正文
技术 2022年11月19日
0 收藏 674 点赞 4,123 浏览 1126 个字

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?

LeetCode OJ 62. Unique Paths

Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.


【题目分析】

给定一个m*n的grid,机器人从左上角出发到达右下角,每次只能向右或者向下移动一步,则到达右下角的不同的路线有多少条?


【思路】

1. 组合数学的思想

在组合数学中关于这个问题有一个专门的讨论,作为组合数入门的一个引入题目。原题目是从坐标点(0, 0)出发,到达另外一个点(m, n)的不同路径有多少条,其中m >= 0, n>=0。

组合数学的思想是这样的,从(0, 0)到达(m, n),无论无论怎么走,总的步数是确定的:m + n,而且肯定是向右移动了m步,向上移动了n步。那么我们先选定向右移动的m步,则剩下的n步就是确定的。所以这是一个组合数C(m+n, m) 或者 C(m+n, n)。

2. 动态规划的思想

动态规划的思想就是在移动过程中计算出到达的每一个小格子的方法数。

(1)到达最上边和最右边方格的方法数是1;

(2)以后到达每一个方格的方法数由它左边和上边的方法数确定,因为我们只能向右和向下移动;结果如下:

LeetCode OJ 62. Unique Paths

LeetCode OJ 62. Unique Paths


【java代码】组合法——由于计算过程中可能会遇到很大的数,要注意溢出的问题。

 public class Solution {
public int uniquePaths(int m, int n) {
m--; n--;
int mn = m + n;
int num = Math.min(m ,n);
double ans = 1;
for(int i=0;i<num;i++)
ans = ans * ((double)(mn - i) / (num-i));
return (int)Math.round(ans);
}
}

【java代码】动态规划

 public class Solution {
public int uniquePaths(int m, int n) {
int[] dp = new int[m];
dp[0] = 1;
for (int i = 0; i < n; i++)
for (int j = 1; j < m; j++)
dp[j] = dp[j - 1] + dp[j];
return dp[m - 1];
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,077
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,552
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,400
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,176
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,813
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,894