DP
状态压缩+DP
leetcode 2306
首先有个hashmap对字符串分组预处理
另外要理解map里面有字符a无字符b的情况,就是答案
class Solution {
public:
long long distinctNames(vector<string>& ideas) {
unordered_map<string, int>m;
for (int i = 0; i < ideas.size(); i++) {
m[ideas[i].substr(1)] |= 1 << (ideas[i][0]-'a');
}
long long ret[26][26] = {0};
long long ans = 0;
for (auto &[_, mask] : m) {
for (int i = 0; i < 26; i++) {
if (((1 << i) & mask) == 0) { //当前没有i,并且有j的情况++
for (int j = 0; j < 26; j++) {
if (((1 << j) & mask) != 0) {
ret[i][j]++;
}
}
} else { //如果当前组有i,那么需要找到没有j的情况,那么就是之前组的结果
for (int j = 0; j < 26; j++) {
if (((1 << j) & mask) == 0) {
ans += ret[i][j];
}
}
}
}
}
return ans*2;
}
};
单调栈+DP
leetcode 2289 重点是理解第二维的计算关系;栈是否空 是一个关键因素
class Solution {
typedef pair<int, int> PII;
public:
int totalSteps(vector<int>& nums) {
stack<PII>s;
int ans = 0;
for (int n:nums) {
int curr = 0;
while (!s.empty() && s.top().first <= n) {
curr = max(curr, s.top().second);
s.pop();
}
if (s.empty()) {
s.push(PII(n, 0));
} else {
s.push(PII(n,curr+1));
ans = max(ans, curr+1);
}
}
return ans;
}
};
搜索
回溯
leetcode 2305
https://blog.csdn.net/weixin_45554139/article/details/104672443
又忘记了,就是分组的意思,主要是found函数的精妙的回退grp-=nums[start]
max_element()
class Solution {
public:
int ans_;
vector<int>grp_;
void dfs(vector<int>& cookies, int index, int k, int len) {
if (index == len) {
auto max = max_element(grp_.begin(),grp_.end());
ans_ = min(ans_, *max);
return;
}
for (int i = 0; i < k; i++) {
grp_[i] += cookies[index];
if (grp_[i] < ans_) {
dfs(cookies, index+1, k, len);
}
grp_[i] -= cookies[index];
}
}
int distributeCookies(vector<int>& cookies, int k) {
ans_ = 0xfffffff;
grp_ = vector<int>(k);
int len = cookies.size();
//sort(cookies.begin(),cookies.end(),[](int a, int b) -> bool { return a > b; });
dfs(cookies, 0, k, len);
return ans_;
}
};
01BFS
https://blog.csdn.net/Mr_dimple/article/details/116864052
leetcode 2290
重点是理解:边界是1,那么pushback,边界是0,pushfront
class Solution {
int m, n;
typedef pair<int, int> PII;
public:
int minimumObstacles(vector<vector<int>>& grid) {
m = grid.size();
n = grid[0].size();
int mod[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
deque<PII>q;
int cost[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cost[i][j] = 0x7fff7fff;
}
}
q.emplace_front(PII(0,0));
cost[0][0] = 0;
while (!q.empty()) {
int x = q.front().first;
int y = q.front().second;
if (x == m-1 && y == n-1) {
break;
}
q.pop_front();
for (int i = 0; i < 4; i++) {
int xx = x + mod[i][0];
int yy = y + mod[i][1];
if (xx < 0 || xx >= m || yy < 0 || yy >= n) {
continue;
}
if (cost[xx][yy] > cost[x][y] + grid[xx][yy]) {
cost[xx][yy] = cost[x][y] + grid[xx][yy];
if (grid[xx][yy]) {
q.emplace_back(PII(xx,yy));
} else {
q.emplace_front(PII(xx,yy));
}
}
}
}
return cost[m-1][n-1];
}
};