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 is there?
Above is a 3 x 7 grid. How many possible unique paths is there?
Note: m and N would be is at most 100.
Idea: The first thought of this problem is recursion, but recursion efficiency is too slow, timeout does not explain. So change the dynamic planning, also is a typical dynamic programming problem.
The specific code is as follows:
public class Solution {public int uniquepaths (int m, int n) { //This method is dynamic programming //State transfer equation F[i][j] = f[i-1][j] + f[i][ J-1]; The value of F[i][j] is the number of paths int[][] f = new int[m][n]; for (int i = 0; i < m; i++)//The first column is assigned a value of 1 f[i][0] = 1; for (int i = 0; i < n; i++)//The first line is assigned a value of 1 f[0][i] = 1; for (int i = 1, i < m; i++) for (int j = 1; j < N; j + +) { f[i][j] = F[i-1][j] + f[i][j-1]; System.out.println ("f[" + i + "[" + j+ "]" + f[i][j]); } Return f[m-1][n-1];//Returns the result value }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 62.Unique Paths (unique Path) thinking and method of solving problems