Middle-题目21:62. Unique Paths

题目原文:
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?
题目大意:
一个机器人从一个m*n的网格的左上角开始走,每次只能向下或向右走一步,问有几种走到右下角的不同走法?
题目分析:
使用dp,设dp[i][j]是从(0,0)点走到(i,j)点的不同走法数,则dp[i][j]=dp[i-1][j]+dp[i][j-1],初始化第一行和第一列为1,(因为只有一行或一列的时候,是唯一走法)
源码:(language:java)

public class Solution {
    public int uniquePaths(int m, int n) {
        int[][] dp=new int[m][n];
        for(int i=0;i<m;i++)
            dp[i][0]=1;
        for(int i=0;i<n;i++)
            dp[0][i]=1;
        for(int i=1;i<m;i++)
            for(int j=1;j<n;j++)
                dp[i][j]=dp[i-1][j]+dp[i][j-1];
        return dp[m-1][n-1];
    }
}

成绩:
1ms,beats 5.98%,众数1ms,77.94%
cmershen的碎碎念:
小学学过奥数的人会对“数最短路线”的算法很熟悉,其实本质是一样的。可是那时候不懂编程,更不懂dp,就知道在网格上累加。

你可能感兴趣的:(Middle-题目21:62. Unique Paths)