回溯

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;

}

};

相关推荐
大闲在人10 分钟前
7. 供应链与制造过程术语:“周期时间”
算法·供应链管理·智能制造·工业工程
小熳芋14 分钟前
443. 压缩字符串-python-双指针
算法
Charlie_lll23 分钟前
力扣解题-移动零
后端·算法·leetcode
chaser&upper24 分钟前
矩阵革命:在 AtomGit 解码 CANN ops-nn 如何构建 AIGC 的“线性基石”
程序人生·算法
weixin_4997715533 分钟前
C++中的组合模式
开发语言·c++·算法
iAkuya1 小时前
(leetcode)力扣100 62N皇后问题 (普通回溯(使用set存储),位运算回溯)
算法·leetcode·职场和发展
近津薪荼1 小时前
dfs专题5——(二叉搜索树中第 K 小的元素)
c++·学习·算法·深度优先
xiaoye-duck1 小时前
吃透 C++ STL list:从基础使用到特性对比,解锁链表容器高效用法
c++·算法·stl
松☆1 小时前
CANN与大模型推理:在边缘端高效运行7B参数语言模型的实践指南
人工智能·算法·语言模型
java干货1 小时前
为什么 “File 10“ 排在 “File 2“ 前面?解决文件名排序的终极算法:自然排序
开发语言·python·算法