1.连续子数组的最大和
- 因为这个数组中含有负数,要不然就可以直接使用双指针的方法来解决这个问题
- 根据经验来讲,可以使用贪心或者动态规划的方法来解决
- 贪心的方法,只要当前的和是负数,那么他对于后续数组和一定是起到削弱的作用的,所以只要是当前的和小于0,那么就应该直接从头开始计算
贪心
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5+10;
int n;
int a[N];
int main()
{
scanf("%d",&n);
for(int i = 1;i<=n;++i)scanf("%d",&a[i]);
int sum = 0,ans = -0x3f3f3f3f;
for(int i = 1;i<=n;++i)
{
sum += a[i];
ans = max(ans,sum);
if(sum < 0)
{
sum = 0;
}
}
printf("%d\n",ans);
return 0;
}
2.跳台阶
class Solution {
int dp[45]{};
public:
int jumpFloor(int n) {
// write code here
dp[1] = 1,dp[2] = 2;
for(int i = 3;i<=n;++i)dp[i] = dp[i-1]+dp[i-2];
return dp[n];
}
};
3.斐波那契数列
class Solution {
int dp[45]{};
public:
int Fibonacci(int n) {
// write code here
dp[1] = dp[2] = 1;
for(int i = 3;i<=n;++i)dp[i] = dp[i-1]+dp[i-2];
return dp[n];
}
};
4.跳台阶扩展问题
class Solution {
int dp[25]{};
public:
int jumpFloorII(int n) {
// write code here
dp[0] = 1;
for(int i = 1;i<=n;++i)
{
for(int j = 0;j<i;++j)
{
dp[i] += dp[j];
}
}
return dp[n];
}
};
5.矩形覆盖
class Solution {
int dp[50]{};
public:
int rectCover(int n) {
if(n==0)return 0;
dp[1] = 1,dp[2] = 2;
for(int i = 3;i<=n;++i)dp[i] = dp[i-1]+dp[i-2];
return dp[n];
}
};
6.礼物的最大价值
class Solution {
int dp[210][210]{};
public:
int maxValue(vector<vector<int> >& grid) {
// write code here
int n = grid.size(),m = grid[0].size();
for(int i = 1;i<=n;++i)
{
for(int j = 1;j<=m;++j)
{
dp[i][j] = max(dp[i-1][j],dp[i][j-1]) + grid[i-1][j-1];
}
}
return dp[n][m];
}
};
7.最长不含重复字符的子字符串
class Solution {
int cnt[128]{};
bool check()
{
for(int i = 0;i<128;++i)if(cnt[i]>1)return false;
return true;
}
public:
int lengthOfLongestSubstring(string s) {
// write code here
int ans = -0x3f3f3f3f;
int n = s.size();
//双指针(滑动窗口)
for(int left = 0,right = 0;right<n;++right)
{
cnt[s[right]]++;
while(!check())
{
cnt[s[left++]]--;
}
if(check())ans = max(ans,right-left+1);
}
return ans;
}
};
8.把数字翻译成字符串
class Solution {
public:
int solve(string s) {
// write code here
int n = s.size();
vector<int>dp(n);
if(s[0] != '0')dp[0] = 1;
if(n == 1)return dp[0];
if(s[1] != '0'&&s[0] != '0')dp[1]++;
int t = (s[0]-'0')*10+s[1]-'0';
if(t>9&&t<=26)dp[1]++;
for(int i = 2;i<n;++i)
{
if(s[i]!='0')dp[i] += dp[i-1];
int t = (s[i-1]-'0')*10+s[i]-'0';
if(t>9&&t<=26)dp[i] += dp[i-2];
}
return dp[n-1];
}
};