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));
}
};