第九天
动态规划——二维数组
class Solution {
public:
int maxValue(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(int i = 0;i < m;i++)
{
for(int j = 0;j < n;j++)
{
if(i==0&&j==0) dp[i][j] = grid[0][0];
else if(i == 0)
{
dp[i][j] = grid[i][j] + dp[0][j-1];
}
else if(j == 0)
{
dp[i][j] = grid[i][j] + dp[i-1][0];
}
else{
dp[i][j] = grid[i][j] + max(dp[i][j-1],dp[i-1][j]);
}
}
}
return dp[m-1][n-1];
}
};
一维数组
优化之后的一维dp保存的是当前上一行的最大价值,然后我们从做到有去更新这个数组即可。
class Solution {
public:
int maxValue(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<int> dp(n+1,0);
for(int i = 0;i < m;i++)
{
for(int j =0;j < n;j++)
{
dp[j+1] = max(dp[j],dp[j+1]) + grid[i][j];
}
}
return dp[n];
}
};
第十天
转为string,一维数组dp存储,动态规划
class Solution {
public:
int translateNum(int num) {
/* vector<char> dp;
itoa(num,dp,10); */
string str = to_string(num);
int n = str.size();
int pre = 1 , cur = 1 , tmp = 1;
for(int i = 0;i < n; i++)
{
if((str[i] == '1' && str[i+1] >= '0' )|| (str[i] == '2' && str[i+1] >= '0' && str[i+1] < '6'))
{
tmp = cur + pre;
//dp[i] = dp[i-1] + dp[i-2];
}
pre = cur;
cur = tmp;
}
return tmp;
}
};
直接用数字来判断,递归
class Solution {
public:
int translateNum(int num) {
if(num == 0) return 1;
return f(num);
}
int f(int num)
{
if(num < 10)
{
return 1;
}
if(num % 100 < 26 && num % 100 > 9) //10-25
{
return f(num/10) + f(num/100);
}
else{
return f(num/10);
}
}
};