【LeetCode 热题 100】最小路径和 / 最长回文子串 / 最长公共子序列 / 编辑距离

目录
- 不同路径
- 最小路径和
- 最长回文子串
- 最长公共子序列
- 编辑距离
不同路径
- 不同路径
class Solution {
public:int uniquePaths(int m, int n) {vector<vector<int>> dp(m + 1, vector<int>(n + 1));dp[0][1] = 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][n];}
};
最小路径和
- 最小路径和
class Solution {
public:int minPathSum(vector<vector<int>>& grid) {int m = grid.size(), n = grid[0].size();vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0x3f3f3f3f));dp[1][0] = dp[0][1] = 0;for (int i = 1; i <= m; i++){for (int j = 1; j <= n; j++){dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i - 1][j - 1];}}return dp[m][n];}
};
最长回文子串
- 最长回文子串
class Solution {
public:string longestPalindrome(string s) {int n = s.size();vector<vector<bool>> dp(n, vector<bool>(n));int begin = 0, len = 1;for (int i = n - 1; i >= 0; i--){for (int j = i; j < n; j++){if (s[i] == s[j]) dp[i][j] = i + 1 < j ? dp[i + 1][j - 1] : true;if (dp[i][j] && j - i + 1 > len){begin = i;len = j - i + 1;}}}return s.substr(begin, len);}
};
最长公共子序列
- 最长公共子序列
class Solution {
public:int longestCommonSubsequence(string text1, string text2) {int m = text1.size(), n = text2.size();vector<vector<int>> dp(m + 1, vector<int>(n + 1));for (int i = 1; i <= m; i++){for (int j = 1; j <= n; j++){if (text1[i - 1] == text2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);}}return dp[m][n];}
};
编辑距离
- 编辑距离
初始化:word1为空串或word2为空串的特殊情况。
class Solution {
public:int minDistance(string word1, string word2) {int m = word1.size(), n = word2.size();vector<vector<int>> dp(m + 1, vector<int>(n + 1));for (int i = 0; i <= m; i++) dp[i][0] = i;for (int i = 0; i <= n; i++) dp[0][i] = i;for (int i = 1; i <= m; i++){for (int j = 1; j <= n; j++){if (word1[i - 1] == word2[j - 1])dp[i][j] = dp[i - 1][j - 1];elsedp[i][j] = min({dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]}) + 1;}}return dp[m][n];}
};
本篇文章的分享就到这里了,如果您觉得在本文有所收获,还请留下您的三连支持哦~
