first of all, we‘re goin to create a 2D array(int[][] grid) to store the number of paths to each position. we get the minimum value of m and n, mark it as min, then look through the row and column of grid[i][i] in each loop, when i == 0, we know we are looking through the toppest row and leftmost column in the array, and set the value of each element in the row and column to be 1. (This is because we can only go to the position in one unique path.) When 0<i<min, the value of the element is grid[i][j] = grid[i-1][j] + grid[i][j-1]; When the loop ends, we will finally get the value of grid[m-1][n-1], which the number of unique paths that we want to obtain.
Code:
public class Solution { public int uniquePaths(int m, int n) { int[][] grid = new int[m][n]; if(m == 0 && n == 0){ grid[m][n] = 1; return grid[m][n]; } int min = m < n? m:n; int i = 0; for(; i < min; i++){ if(i == 0){ for(int j = 0; j < m; j++) grid[j][0] = 1; for(int j = 0; j < n; j++) grid[0][j] = 1; } else{ for(int j = i; j < m; j++) grid[j][i] = grid[j-1][i] + grid[j][i-1]; for(int j = i; j < n; j++) grid[i][j] = grid[i-1][j] + grid[i][j-1]; } } return grid[m-1][n-1]; } }
时间: 2024-10-23 20:03:30