【LeetCode】62.Unique Paths解题报告
tags: Array DP
题目地址:https://leetcode.com/problems/unique-paths/#/description
题目描述:
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?
Above is a 3 x 7 grid. How many possible unique paths are there?
Note:m and n will be at most 100.
题意:机器人从左顶点走到右顶点,问多少种走法,只能向右和向下。
分析:本题其实就是一个组合问题,用公式可以直接得到,然而,题还可以用dp做,但是刚开始刷题,dp解法以后补上。公式其实就是(m+n)!/m!*n!
Solutions:
public class Solution {
public int uniquePaths(int m, int n) {
if(m == 1 || n == 1)
return 1;
m--;
n--;
if(m < n) { // Swap, so that m is the bigger number
m = m + n;
n = m - n;
m = m - n;
}
long res = 1;
int j = 1;
for(int i = m+1; i <= m+n; i++, j++){ // Instead of taking factorial, keep on multiply & divide
res *= i;
res /= j;
}
return (int)res;
}
}
Date:2017年6月23日