回溯

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;

}

};

相关推荐
2301_8227032044 分钟前
Flutter 框架跨平台鸿蒙开发 - 创意声音合成器应用
算法·flutter·华为·harmonyos·鸿蒙
cmpxr_1 小时前
【C】数组名、函数名的特殊
c语言·算法
KAU的云实验台1 小时前
【算法精解】AIR期刊算法IAGWO:引入速度概念与逆多元二次权重,可应对高维/工程问题(附Matlab源码)
开发语言·算法·matlab
会编程的土豆1 小时前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
大熊背2 小时前
如何利用Lv值实现三级降帧
算法·自动曝光·lv·isppipeline
大尚来也2 小时前
驾驭并发:.NET多线程编程的挑战与破局之道
java·前端·算法
向阳而生,一路生花2 小时前
深入浅出 JDK7 HashMap 源码分析
算法·哈希算法
君义_noip3 小时前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
摸个小yu3 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
汀、人工智能3 小时前
[特殊字符] 第93课:太平洋大西洋水流问题
数据结构·算法·数据库架构·图论·bfs·太平洋大西洋水流问题