动态规划

674. 最长连续递增序列
class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        vector<int>dp;
        if(nums.size()==0) return 0;
        int res =1,count=1;
        for(int i=0;i<nums.size()-1;i++){
            if(nums[i]<nums[i+1]) count++;
            else count = 1;
            res = max(res,count);
        }
        return res;
    }
};
5. 最长回文子串
class Solution:
    def longestPalindrome(self, s: str) -> str:
        
        res = ""
        dp = [[False] * len(s) for i in range(len(s))]
        for i in range(len(s)-1, -1, -1):
            for j in range(i, len(s)):
                dp[i][j] = (s[i] == s[j]) and (j - i < 3 or dp[i+1][j-1])
                if dp[i][j] and (j - i + 1 > len(res)):
                    res = s[i:j+1]
        return res
72. 编辑距离

dp来做,设dp[i][j]为word1的前i个字符到word2的前j个字符的编辑距离。则状态转移方程为:

dp[i][j]=min(dp[i][j-1]+1, dp[i-1][j]+1, dp[i-1][j-1], dp[i-1][j-1] +1)

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, 0));
        for (int i = 0; i <= m; ++i)
            dp[i][0] = i;
        for (int j = 1; j <= n; ++j)
            dp[0][j] = j;
        for (int i = 1; i <= m; ++i){
            for (int j = 1; j <= n; ++j){
                int a = (word1[i-1] == word2[j-1] ? dp[i - 1][j - 1] : dp[i - 1][j - 1] + 1);
                dp[i][j] = min(min(dp[i][j - 1] + 1, dp[i - 1][j] + 1), a);
            }
        }
        return dp[m][n];
    }
};
198. 打家劫舍
class Solution {
public:
    int rob(vector<int>& nums) {
        int temp1=0, temp2=0, re=0;
        for(int x:nums)
        {
            re=max(temp1+x,temp2);
            temp1=temp2;
            temp2=re;
        }
        return re;
    }
};
213. 打家劫舍 II
class Solution {
public:
    int help(vector<int>& nums, int l, int r){
        int temp1=0, temp2=0, re=0;
        for(int i=l; i<=r; ++i){
            re=max(temp1+nums[i], temp2);
            temp1=temp2;
            temp2=re;
        }
        return re;
    }
 
    int rob(vector<int>& nums) {
        int n = nums.size();
        if(n==0) return 0;
        else if(n==1) return nums[0];
        else if(n==2) return max(nums[0],nums[1]);
        return max(help(nums, 0, nums.size()-2), help(nums, 1, nums.size()-1));
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值