回溯

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;

}

};

相关推荐
NAGNIP3 小时前
万字长文!回归模型最全讲解!
算法·面试
知乎的哥廷根数学学派3 小时前
面向可信机械故障诊断的自适应置信度惩罚深度校准算法(Pytorch)
人工智能·pytorch·python·深度学习·算法·机器学习·矩阵
666HZ6664 小时前
数据结构2.0 线性表
c语言·数据结构·算法
实心儿儿5 小时前
Linux —— 基础开发工具5
linux·运维·算法
charlie1145141916 小时前
嵌入式的现代C++教程——constexpr与设计技巧
开发语言·c++·笔记·单片机·学习·算法·嵌入式
清木铎7 小时前
leetcode_day4_筑基期_《绝境求生》
算法
清木铎7 小时前
leetcode_day10_筑基期_《绝境求生》
算法
j_jiajia7 小时前
(一)人工智能算法之监督学习——KNN
人工智能·学习·算法
源代码•宸8 小时前
Golang语法进阶(协程池、反射)
开发语言·经验分享·后端·算法·golang·反射·协程池
Jasmine_llq9 小时前
《CF280C Game on Tree》
数据结构·算法·邻接表·深度优先搜索(dfs)·树的遍历 + 线性累加统计