leetcode 62 不同路径
// 深度优先搜索算法
// 图论算法,不断递归找到新路径
class Solution {private:int dfs(int i, int j, int m, int n){if(i > m || j > n) return 0;if(i == m && j == n) return 1;return dfs(i+1, j, m, n) + dfs(i, j+1, m, n);}public:int uniquePaths(int m, int n) {return dfs(1, 1, m, n);}
};// 动态规划方法
// 动态规划5部曲
// 1.dp数组含义:dp[i][j]:从[0,0]出发到达[i,j]一共有多少种不同的路径
// 2.递推公式:dp[i][j] = dp[i-1][j] +dp[i][j-1]
// 3.dp数组初始化: dp[i][0] = 1; dp[0][j] = 1
// 4.遍历顺序:从左到右一层层遍历
// 5.打印dp数组class Solution {
public:int uniquePaths(int m, int n) {vector<vector<int>> dp(m, vector<int>(n, 0));for(int i=0; i<m; ++i)dp[i][0] = 1;for(int j=0; j<n; ++j)dp[0][j] = 1;for(int i=1; i<m; ++i){ for(int j=1; j<n; ++j){dp[i][j] = dp[i-1][j] + dp[i][j-1];} }return dp[m-1][n-1];}
};// 组合数学方法
// C m-1 m+n-2class Solution {
public:int uniquePaths(int m, int n) {long long result = 1;long long numerator = m + n - 2; // 分子int denominator = m-1; // 分母int count = m - 1;while(count--){result *= (numerator--);while(denominator !=0 && result % denominator == 0){result /= denominator;denominator--;}}return result;}
};
leetcode 63.不同路径Ⅱ
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {int m = obstacleGrid.size();int n = obstacleGrid[0].size();vector<vector<int>> dp(m, vector<int>(n, 0));int flag = 0;for(int i=0; i<m; ++i){ if(obstacleGrid[i][0] == 1)flag = 1;if(flag)dp[i][0] = 0;elsedp[i][0] = 1;}flag = 0;for(int j=0; j<n; ++j){if(obstacleGrid[0][j] == 1)flag = 1;if(flag)dp[0][j] = 0;elsedp[0][j] = 1;}for(int i=1; i<m; ++i){ for(int j=1; j<n; ++j){ if(obstacleGrid[i][j] == 0)dp[i][j] = dp[i-1][j] + dp[i][j-1];elsedp[i][j] = 0;} }// for(auto hang: dp)// {// for(auto col: hang)// cout << col;// }return dp[m-1][n-1];}
@ 代码随想录