LeetCode-62:Unique Paths

来源:互联网 发布:ubuntu卸载nvidia驱动 编辑:程序博客网 时间:2024/06/16 05:08

原题描述如下:

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.

题意给定一个放个,左上角有一个机器人,该机器人每次只能向右或者向下走一步,问,该机器人从左上角走到右下角一共有几种走法?

解题思路:

看似简单一道题,就是mxn的格子里从左上角走到右下角有多少种走法,只能向右或向下走。
分析:向下需要 m-1 步,向右需要 n-1 步,所以总的走法就是 C(m-1,  m-1+n-1) 或者 C(n-1, m-1+n-1)。

Java代码:

public class Solution {
    public int uniquePaths(int m, int n) {
        int[][] dp = new int[m][n];
        
        for(int i=0; i<m; ++i){
            for(int j=0; j<n; ++j){
                if(i == 0 || j == 0){
                    dp[i][j] = 1;
                }else{
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
                }
            }
        }
        
        return dp[m-1][n-1];
    }
}
0 0
原创粉丝点击