每日温度
方法一:
暴力求解,超时。
代码:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
vector<int> res;
int n = temperatures.size();
for(int i = 0; i < n; i++) {
bool flag = false;
int cnt = 0;
for(int j = i + 1; j < n; j++) {
cnt++;
if(temperatures[j] > temperatures[i]) {
flag = true;
break;
}
}
if(flag) {
res.push_back(cnt);
}else {
res.push_back(0);
}
}
return res;
}
};
方法二:
单调栈:定义一个栈保存下标,遍历原数组,如果当前栈为空,则当前下标入栈,否则:定义当前访问的元素为cur,如果cur大于栈顶的下标处的值,则说明栈顶的下标处碰到了第一个大于它的值,填入结果,一直出栈直到栈顶下标处的值大于等于当前值,当前的下标入栈。
代码:
class Solution {
public:
vector<int> dailyTemperatures(vector<int>& temperatures) {
int n = temperatures.size();
vector<int> res(n, 0);
stack<int> stk;
for(int i = 0; i < n; i++) {
int cur = temperatures[i];
while(!stk.empty() && cur > temperatures[stk.top()]) {
res[stk.top()] = i - stk.top();
stk.pop();
}
stk.push(i);
}
return res;
}
};
分割等和子集
分析:
动态规划,dp[i][j] = true表示从下标[0, i]处中可以选择几个数,使得它们的和等于j。
代码:
class Solution {
public:
bool canPartition(vector<int>& nums) {
int n = nums.size();
if(n < 2) {
return false;
}
int _max = 0, sum = 0;
for(int x : nums) {
sum += x;
_max = max(_max, x);
}
if(sum & 1) {
return false;
}
int target = sum / 2;
if(_max > target) {
return false;
}
vector<vector<int>> dp(n, vector<int>(target + 1, 0));
for (int i = 0; i < n; i++) {
dp[i][0] = true;
}
dp[0][nums[0]] = true;
for (int i = 1; i < n; i++) {
int num = nums[i];
for (int j = 1; j <= target; j++) {
if (j >= num) {
dp[i][j] = dp[i - 1][j] | dp[i - 1][j - num];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[n - 1][target];
}
};