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?
Analysis: This problem can be solved by dynamic programming, F[I][J] represents the number of paths from (0,0) to (I,J), recursion formula is f[i][j] = F[i-1][j] + f[i][j-1]. Time complexity O (n^2), Spatial complexity O (n^2). The code is as follows:
classSolution { Public: intUniquepaths (intMintN) {intF[m][n]; for(inti =0; I < n; i++) f[0][i] =1; for(inti =0; I < m; i++) f[i][0] =1; for(inti =1; I < m; i++) for(intj =1; J < N; J + +) F[i][j]= f[i][j-1] + f[i-1][j]; returnf[m-1][n-1]; }};
In fact, when using dynamic programming, we can use a scrolling array instead of a two-dimensional array. The code is as follows:
classSolution { Public: intUniquepaths (intMintN) {vector<int> f (N,0); f[0] =1; for(inti =0; I < m; i++) for(intj =1; J < N; J + +) F[j]= F[j] + f[j-1]; returnf[n-1]; }};
Leetcode:unique Paths