目录
class Solution {
public:
int uniquePaths(int m, int n) {
vector<vector<int>>dp(m,vector<int>(n));
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 - 1][j];
dp[i][j] += dp[i][j - 1];
}
}
return dp[m - 1][n - 1];
}
};
时间复杂度O(mn)
空间复杂度O(mn)
class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
vector<vector<int>>dp(text1.size() + 1,vector<int>(text2.size() + 1));
for(int i = 1;i <= text1.size();i++){
for(int j = 1;j <= text2.size();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[text1.size()][text2.size()];
}
};
时间复杂度O(mn)
空间复杂度O(mn)
class Solution {
public:
int maxProfit(vector<int>& prices, int fee) {
int res = 0;
int pay = fee + prices[0];
for(int i = 1;i < prices.size();i++){
if(prices[i] > pay){
res += prices[i] - pay;
pay = prices[i];
}else if(pay > prices[i] + fee){
pay = prices[i] + fee;//开始新的一轮
}
}
return res;
}
};
时间复杂度O(n)
空间复杂度O(1)
?
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>>dp(word1.size() + 1,vector<int>(word2.size() + 1));
for(int i = 0;i <= word1.size();i++)dp[i][0] = i;
for(int i = 0;i <= word2.size();i++)dp[0][i] = i;
for(int i = 1;i <= word1.size();i++){
for(int j = 1;j <= word2.size();j++){
dp[i][j] = min(dp[i - 1][j],dp[i][j - 1]) + 1;//增和删
if(word1[i - 1] != word2[j - 1]){
dp[i][j] = min(dp[i - 1][j - 1] + 1,dp[i][j]);
}else{
dp[i][j] = min(dp[i - 1][j - 1],dp[i][j]);
}
}
}
return dp[word1.size()][word2.size()];
}
};
时间复杂度O(mn)
空间复杂度O(mn)