博客
关于我
[LeetCode] 40. Combination Sum II
阅读量:249 次
发布时间:2019-03-01

本文共 1151 字,大约阅读时间需要 3 分钟。

回溯法是解决组合数问题的一种高效方法。以下是基于回溯法实现的组合数问题解决方案:

#include 
#include
using namespace std;void cb2help(vector
&res, vector
&v, int target, int i, vector
&recp) { if (target < 0) return; if (target == 0) { res.push_back(recp); return; } for (unsigned int k = i; k < v.size(); ++k) { if (k > i && v[k] == v[k-1]) continue; recp.push_back(v[k]); cb2help(res, v, target - v[k], k + 1, recp); recp.pop_back(); if (target - v[k] < 0) return; }}vector
combinationSum2(vector
v, int target) { sort(v.begin(), v.end()); vector
res; vector
recp; cb2help(res, v, target, 0, recp); return res;}

代码主要包含以下几个部分:

  • void cb2help 函数:这是回溯法的核心函数,负责从当前位置开始,尝试所有可能的数值组合。
  • combinationSum2 函数:这是最终的入口函数,负责对数组进行排序并调用回溯函数。
  • 回溯法的实现逻辑:从当前索引开始,遍历所有可能的数值。如果当前数值与前一个数值相同,则跳过;否则,将其加入当前组合,递归调用回溯函数,并在返回时移除当前数值,继续尝试下一个数值。
  • 需要注意的点是:当当前层的数值与前一个数值相同时,会跳过。这样可以避免重复计算相同的组合数。

    回溯法的时间复杂度主要取决于组合数的数量级。如果目标组合数较小,回溯法的效率较高;但如果目标组合数较多,可能会导致性能问题。

    转载地址:http://erfx.baihongyu.com/

    你可能感兴趣的文章
    poj 2406 还是KMP的简单应用
    查看>>
    POJ 2431 Expedition 优先队列
    查看>>
    Qt笔记——获取位置信息的相关函数
    查看>>
    POJ 2484 A Funny Game(神题!)
    查看>>
    POJ 2486 树形dp
    查看>>
    POJ 2488:A Knight&#39;s Journey
    查看>>
    SpringBoot为什么易学难精?
    查看>>
    poj 2545 Hamming Problem
    查看>>
    poj 2723
    查看>>
    poj 2763 Housewife Wind
    查看>>
    Qt笔记——模型/视图MVD 文件目录浏览器软件
    查看>>
    POJ 2892 Tunnel Warfare(树状数组+二分)
    查看>>
    poj 2965 The Pilots Brothers' refrigerator-1
    查看>>
    poj 3026( Borg Maze BFS + Prim)
    查看>>
    POJ 3041 - 最大二分匹配
    查看>>
    POJ 3041 Asteroids(二分匹配模板题)
    查看>>
    Qt笔记——标准文件对话框QFileDialog
    查看>>
    poj 3083 Children of the Candy Corn
    查看>>
    POJ 3083 Children of the Candy Corn 解题报告
    查看>>
    POJ 3253 Fence Repair C++ STL multiset 可解 (同51nod 1117 聪明的木匠)
    查看>>