Java for LeetCode 062 Unique Paths

本文介绍了一种计算机器人从网格左上角到右下角所有可能路径数量的方法。提供了两种解决方案,一种基于排列组合利用BigInteger避免溢出,另一种采用动态规划优化计算效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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?

解题思路一:

很明显,答案是C(m+n-2,n-1),是一个排列组合问题,直接使用int进行操作的话,会发生数据溢出,不过好在我们有BigInteger,JAVA实现如下:

import java.math.BigInteger;

public class Solution {
    public int uniquePaths(int m, int n) {
	        return Cmn(m,n).intValue();
	    }
	    static BigInteger Cmn(int m, int n){
	    	return Amn(m + n - 2, n - 1).divide(factorial(n - 1));
	    }
	    static BigInteger Amn(int m, int n) {
	        if (n == 0)
	            return BigInteger.valueOf(1);
	        if (n == 1)
	            return BigInteger.valueOf(m);
	        else
	            return Amn(m - 1, n - 1).multiply(BigInteger.valueOf(m));
	    }
	 
	    static BigInteger factorial(int n) {
	        if (n == 1 || n == 0)
	            return BigInteger.valueOf(1);
	        else
	            return factorial(n - 1).multiply(BigInteger.valueOf(n));
	    }
}

 

 解题思路二:

很明显uniquePaths(int m, int n)=uniquePaths(int m-1, int n)+uniquePaths(int m, int n-1),结果提交发现Time Limit Exceeded,看来不能直接用递归计算。不过基于上述结论,我们可以采用dp的方法,开一个数组v[j]表示经过i步右移和j步下移后达到(i,j)的路径数目,前进方法为v[j] += v[j - 1],表示v[j]由从左边过来的v[j-1]和从上面下来的前一个v[j]组成,JAVA实现如下:

	static public int uniquePaths(int m, int n) {
		int[] v = new int[n];
		for (int i = 0; i < v.length; i++)
			v[i] = 1;
		for (int i = 1; i < m; ++i)
			for (int j = 1; j < n; j++)
				v[j] += v[j - 1];
		return v[n - 1];
	}

 

转载于:https://www.cnblogs.com/tonyluis/p/4506913.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值