回溯

lc

lc2121

hash抽象分组后前缀和

注意 这个地方的下标个数统计要-1...

++(ll)b[i] * (m - i-1);++

class Solution {

typedef long long ll;

public:

vector<long long> getDistances(vector<int>& arr)

{

int n=arr.size();

vector<ll> ret(n);

unordered_map<int,vector<int>> hash;

for(int i=0;i<n;i++)

{

hash[arr[i]].push_back(i);

}

for(auto& [a,b]:hash)

{

int m=b.size();

vector<ll> p(m+1);

for(int i=1;i<=m;i++)

p[i]=p[i-1]+b[i-1];

for(int i=0;i<m;i++)

{

ll f = (ll)b[i] * i - p[i];

ll e = (p[m] - p[i+1]) - ++(ll)b[i] * (m - i-1);++

ret[b[i]] = f + e;

}

}

return ret;

}

};

lc320

优雅的回溯

//缩写

dfs(p + 1, cnt + 1);

//结算 +cnt +p后

dfs(p + 1, 0); // p+1、重置cnt为0

数字串回溯tricks:

++if (cnt > 0)++

++path.erase(path.end() - to_string(cnt).size(), path.end());++

class Solution {

public:

vector<string> generateAbbreviations(string word)

{

int n = word.size();

string path;

vector<string> ret;

auto dfs = [&](this auto&& dfs,int p, int cnt)

{

if (p == n) {

if (cnt > 0)

path += to_string(cnt);

ret.push_back(path);

++if (cnt > 0) path.erase(path.end() - to_string(cnt).size(), path.end());//回溯++

return;

}

//缩写

dfs(p + 1, cnt + 1);

// 结算+保留

if (cnt > 0)

path += to_string(cnt);

path += word[p];

++dfs(p + 1, 0); // p+1、重置cnt为0++

// 回溯

path.pop_back();

if (cnt > 0) {

path.erase(path.end() - to_string(cnt).size(), path.end());

}

};

dfs(0, 0);

return ret;

}

};

相关推荐
鲨莎分不晴6 小时前
强化学习第四课 —— 从“粗糙草稿”到“第一性原理”:为 REINFORCE 算法正名
算法
CoovallyAIHub6 小时前
震后如何快速评估上万栋建筑?俄亥俄州立大学提出混合智能检测方案
深度学习·算法·计算机视觉
Voyager_46 小时前
算法学习记录16——Floyd 判圈算法(环形链表 II)
学习·算法·链表
代码游侠6 小时前
学习笔记——进程控制函数
linux·运维·笔记·学习·算法
小O的算法实验室6 小时前
2022年CIE SCI2区TOP,双向交替搜索 A* 算法的移动机器人全局路径规划,深度解析+性能实测
算法·论文复现·智能算法·智能算法改进
木头左6 小时前
多任务联合训练框架下的遗忘门协同优化趋势跟踪与均值回归双目标平衡
算法·均值算法·回归
xu_yule6 小时前
算法基础-(单调队列)
算法·单调队列
代码不停6 小时前
Java递归综合练习
java·开发语言·算法·回归
前端小白在前进6 小时前
力扣刷题:删除排序链表的重复元素Ⅱ
算法·leetcode·链表