Java for LeetCode 062 Unique Paths

时间:2015-05-15 22:41:05   收藏:0   阅读:173

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?

解题思路一:

BigInteger,JAVA实现如下:

import java.math.BigInteger;

public class Solution {
	public int uniquePaths(int m, int n) {
		if (n > m) {
			int temp = n;
			n = m;
			m = temp;
		}
		return Amn(m + n - 2, n - 1).divide(factorial(n - 1)).intValue();
	}

	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));
	}
}

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!