Leetcode-62. Unique Paths

来源:互联网 发布:手机怎么成为网络歌手 编辑:程序博客网 时间:2024/06/11 18:34

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。

博客链接:mcf171的博客

---------------

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.

在这个图中,机器人必须要往下走两步并且往右走六步。其实这个问题就可以转换为我们有多少种方式将两步插入到六步种。
换成一个更通俗易懂的问题:有六个红球,两个白球,我们有多少种方式将白球插入到红球中。
但是这个问题仍然不好解。那么我们再次转换问题,如果有8个球,我们有多少种方式选6个红球或者说选2个白球。这个问题太简单了,就是一个组合问题,结果就是C^6_8 或者C^2_8。
那么延伸到m和n就是C^(m-1) _ (m+n-2) 或者 C^(n-1)_(m+n-2)Your runtime beats 80.93% of java submissions.

public class Solution {    public int uniquePaths(int m, int n) {m = m-1;n = n-1;        double numerator = 1,denominator = 1;int minNum = Math.min(m,n);int maxNum = Math.max(m,n);for(int i = (m + n); i > maxNum ; i --) numerator *= i;for(int i = minNum; i > 0 ; i --) denominator *= i;return (int)(numerator/denominator);    }}




0 0
原创粉丝点击