LeetCode 75|動的プログラミング - 多次元

目次

62 の異なるパス

1143 最長共通部分列

714 手数料を含めた株の売買に最適な時期

72 編集距離


62 の異なるパス

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)

1143 最長共通部分列

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)

714 手数料を含めた株の売買に最適な時期

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)

72 編集距離

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)

おすすめ

転載: blog.csdn.net/m0_72832574/article/details/135200025