回溯剪枝trick

lc638

dfs+memo

比"不买任何大礼包单买商品"和"买各个可用大礼包后再买剩余商品"的花费,找出满足购物需求的最低价格。

class Solution {

public:

// 不同的needs所需的价格

map<vector<int>, int> _cache;

int shoppingOffers(vector<int>& price, vector<vector<int>>& special, vector<int>& needs)

{

return dfs(needs, price, special);

}

int dfs(vector<int> needs, vector<int>& price, vector<vector<int>>& special) {

// 如果子问题已经计算过 直接返回

if (_cache[needs]) { return _cache[needs]; }

int ans = 0;

// 最弱的方式;不购买大礼包

for (int i = 0; i < needs.size(); i++) {

ans += needs[i] * price[i];

}

// 遍历每个礼包,购买它,看看是不是能获得更便宜的价格

for (int i = 0; i < special.size(); i++) {

vector<int> next = needs;

bool valid = true;

// 因为购买的数量需要正好是needs 所以大礼包的某个商品不能超过needs的商品数量

for (int item = 0; item < price.size(); item++) {

if (special[i][item] > needs[item]) {

valid = false;

break;

}

}

// 当前大礼包不符合要求 跳过

if (!valid) continue;

// 当前大礼包符合要求,用next数组记录买过大礼包之后还需要买多少商品

for (int item = 0; item < price.size(); item++) {

++next[item] -= special[i][item];++

}

++ans = min(ans, dfs(next, price, special) + special[i].back());++

}

// 更新cache

_cache[needs] = ans;

return ans;

}

};

lc473

先判断火柴总长度是否能分成4等份且无超长火柴

再用回溯尝试把每根火柴分配到正方形的四条边,看是否能让每条边长度都等于目标边长

++// 剪枝:避免重复探索相同长度火柴的无效分支
if (i > 0 && matchsticks[index] == matchsticks[index - 1] && !vis[index - 1]) {
continue;
++

class Solution {

public:

bool makesquare(vector<int>& matchsticks) {

int sum = 0;

for (int m : matchsticks) sum += m;

if (sum % 4 != 0) return false;

int target = sum / 4;

sort(matchsticks.rbegin(), matchsticks.rend());

for (int m : matchsticks) if (m > target) return false;

vector<int> edges(4, 0);

vector<bool> vis(matchsticks.size(), false); // 标记火柴是否已使用

return backtrack(matchsticks, edges, 0, target, vis);

}

bool backtrack(vector<int>& matchsticks, vector<int>& edges, int index, int target, vector<bool>& vis)

{

if (index == matchsticks.size()) return true;

for (int i = 0; i < 4; ++i) {

// 剪枝1:当前边放入火柴后长度不超过target

if (edges[i] + matchsticks[index] <= target) {

++// 剪枝2:避免重复探索相同长度火柴的无效分支
if (i > 0 && matchsticks[index] == matchsticks[index - 1] && !vis[index - 1]) {
continue;
++

}

++edges[i] += matchsticks[index];++

vis[index] = true;

if (backtrack(matchsticks, edges, ++index + 1,++ target, vis))

return true;

edges[i] -= matchsticks[index];

vis[index] = false;

}

// 剪枝3:当前边长度为0,后续边无需重复处理

if (edges[i] == 0) break;

}

return false;

}

};

相关推荐
WolfGang00732119 分钟前
代码随想录算法训练营Day48 | 108.冗余连接、109.冗余连接II
数据结构·c++·算法
崇山峻岭之间1 小时前
C++ Prime Plus 学习笔记041
c++·笔记·学习
_风华ts1 小时前
虚函数与访问权限
c++
1001101_QIA1 小时前
C++中不能复制只能移动的类型
开发语言·c++
闻缺陷则喜何志丹1 小时前
【组合数学】P9418 [POI 2021/2022 R1] Impreza krasnali|普及+
c++·数学·组合数学
晨曦夜月2 小时前
头文件与目标文件的关系
linux·开发语言·c++
刃神太酷啦2 小时前
C++ list 容器全解析:从构造到模拟实现的深度探索----《Hello C++ Wrold!》(16)--(C/C++)
java·c语言·c++·qt·算法·leetcode·list
有点。3 小时前
C++ ⼀级 2023 年09 ⽉
c++
LXS_3573 小时前
Day 16 C++提高之模板
开发语言·c++·笔记·学习方法
wyw00003 小时前
鸿蒙开发-如何将C++侧接收的PixelMap转换成cv::mat格式
c++·华为·harmonyos