回溯剪枝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 (_cacheneeds) { return _cacheneeds; }

int ans = 0;

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

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

ans += needsi * pricei;

}

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

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 (specialiitem > needsitem) {

valid = false;

break;

}

}

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

if (!valid) continue;

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

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

++nextitem -= specialiitem;++

}

++ans = min(ans, dfs(next, price, special) + speciali.back());++

}

// 更新cache

_cacheneeds = ans;

return ans;

}

};

lc473

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

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

++// 剪枝:避免重复探索相同长度火柴的无效分支
if (i > 0 && matchsticksindex == matchsticksindex - 1 && !visindex - 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 (edgesi + matchsticksindex <= target) {

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

}

++edgesi += matchsticksindex;++

visindex = true;

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

return true;

edgesi -= matchsticksindex;

visindex = false;

}

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

if (edgesi == 0) break;

}

return false;

}

};

相关推荐
_wyt0016 小时前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾10 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you11 小时前
constexpr函数
c++
凡人叶枫11 小时前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫11 小时前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss11 小时前
BRpc使用
c++·rpc
-森屿安年-12 小时前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream12 小时前
Cartographer详细讲解
c++·人工智能·自动驾驶
森G12 小时前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
碧海蓝天202212 小时前
C++法则24:在标准 C++ 中,没有任何可移植的方式判断指针 T* pt 指向的内存位置是否已经 构造了对象,程序员必须手动跟踪哪些元素已构造。
java·开发语言·c++