Leetcode|组合|40.组合总和II(排序+first+跳过重复元素+右分支收紧)

在这里插入图片描述

1 回溯法(排序+first索引+跳过重复元素+右分支收紧)

结合问题性质,基于回溯模板额外添加的主要步骤如下

  • 排序使重复元素相邻
  • first索引剪枝左分支不同序重复解
  • 跳过重复元素(两者相同且nums[i-1]用过则nums[i]不再用)
  • 右分支收紧(candidates[i] + sum > target
class Solution {
    int size;
    vector<vector<int>> solution;
    vector<int> path;
public:
    void backtrack(vector<int>& candidates, int target, int sum, int first) {
        if (sum == target) {
            solution.emplace_back(path);
            return;
        }
        // 2.first索引剪枝左分支不同序重复解
        for (int i = first; i < size; i++) {
            // 3.右分支收紧,进一步剪枝
            if (candidates[i] + sum > target) break;
            // 4.first辅助跳过重复元素,两者相同且nums[i-1]用过则nums[i]不再用, 需结合[2]inPath实现
            if (i > first && candidates[i] == candidates[i-1]) continue;
            path.emplace_back(candidates[i]);
            backtrack(candidates, target, sum + candidates[i], i + 1);
            path.pop_back();
        }
    }
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        size = candidates.size();
        // 1.升序排序
        sort(candidates.begin(), candidates.end());
        backtrack(candidates, target, 0, 0);
        return solution;
    }
};

可见,确实省内存了
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SL_World

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值