62.不同路径
简单题目自己就可以写出来,注意下创建二维vector的方法就可以, dp table如下
class Solution {
public:int uniquePaths(int m, int n) {vector<vector<int>> dp(m,vector<int>(n,0));for (int i = 0; i < n; i ++) {dp[0][i] = 1;}for (int i = 0; i < m; i ++) {dp[i][0] = 1;}for (int i = 1; i < m; i++) {for (int j = 1; j < n; j++) {dp[i][j] = dp[i][j-1] + dp[i-1][j];}}return dp[m-1][n-1];}
};
63. 不同路径 II
简单
题目会传入一个obstacle table里面有记录0和1代表有没有障碍,另外我们自己创建一个dp table并且初始化为0,然后再遍历的时候判断这个obstacletable里面的数字是不是1, 如果是的话就让他为零;
class Solution {
public:int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {int m =obstacleGrid.size(); //二维数组直接取size取到的是行int n = obstacleGrid[0].size(); //记一下取列的方法,把第一行取出来然后取size();if (obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) return 0;vector<vector<int>> dp(m, vector<int>(n,0));for (int i = 0; i < m && obstacleGrid[i][0] != 1; i++) {dp[i][0] =1;} for (int i = 0; i < n && obstacleGrid[0][i] != 1; i++) {dp[0][i] =1;} for (int i = 1; i < m; i++) {for (int j =1; j < n; j++) {if (obstacleGrid[i][j] == 1) {// dp[i][j] = 0; 这么写不对因为还会把这个格子置1之后,还会接着走下面的程序,又把1给替换掉了continue;}dp[i][j] = dp[i-1][j] + dp[i][j-1];}}return dp[m-1][n-1];}
};