I
动态规划,一次性构造,查询。采用回溯法会超时
class Solution { public: int grid[100][100]; int uniquePaths(int m, int n) { if(grid[m-1][n-1]==0) construct(); return grid[m-1][n-1]; } void construct() { grid[0][0]=1; for(int i=1;i<100;i++) { grid[i][0]=1; } for(int i=1;i<100;i++) { grid[0][i]=1; } for(int i=1;i<100;i++) { for(int j=1;j<=i;j++) { grid[i][j]=grid[i][j-1]+grid[i-1][j]; grid[j][i]=grid[i][j]; } } } };
II
有障碍物的情况
class Solution { public: int grid[100][100]; int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid) { int m=obstacleGrid.size(); if(m==0)return 0; int n=obstacleGrid[0].size(); for(int i=0;i<m;i++) { for(int j=0;j<n;j++) grid[i][j]=0; } if(!obstacleGrid[0][0]) grid[0][0]=1; for(int i=1;i<m;i++) { if(!obstacleGrid[i][0]) grid[i][0]=grid[i-1][0]; } for(int i=1;i<n;i++) { if(!obstacleGrid[0][i]) grid[0][i]=grid[0][i-1]; } for(int i=1;i<m;i++) { for(int j=1;j<n;j++) { if(!obstacleGrid[i][j]) { grid[i][j]+=grid[i-1][j]+grid[i][j-1]; } } } return grid[m-1][n-1]; } };