【LeetCode】62.Unique Paths解题报告

来源:互联网 发布:directx 11游戏编程 编辑:程序博客网 时间:2024/05/16 18:48

【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日