博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[leetcode-40-Combination Sum II]
阅读量:7116 次
发布时间:2019-06-28

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

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8

A solution set is: 

[  [1, 7],  [1, 2, 5],  [2, 6],  [1, 1, 6]]

思路:

典型回溯法,需要注意的就是存在重复情况的处理。

 

 

void combine(vector
>& res, vector
& candidates, vector
& cantemp,int begin, int target) { if (target < 0) return; if ( target == 0) { res.push_back(cantemp); return; } for (int i = begin; i < candidates.size();i++) { //if (candidates[i]>target)return; if (i && candidates[i]==candidates[i-1]&& i>begin) continue;//避免重复元素 cantemp.push_back(candidates[i]); combine(res, candidates, cantemp, i + 1, target - candidates[i]); cantemp.pop_back(); } } vector
> combinationSum2(vector
& candidates, int target) { vector
> res; if (candidates.size() == 0)return res; sort(candidates.begin(), candidates.end()); vector
cantemp; combine(res, candidates, cantemp, 0, target); return res; }

参考:

转载于:https://www.cnblogs.com/hellowooorld/p/7009000.html

你可能感兴趣的文章
FastReport微调
查看>>
nginx下的文件下载防盗链(HttpAccessKeyModule)
查看>>
Linq延迟执行(转)
查看>>
Django实战(3):Django也可以有scaffold
查看>>
简单缓存 datatable
查看>>
MFC界面的完善
查看>>
WPF&SL之Basic MVVM
查看>>
On :target
查看>>
最新30幅动人心脾的优秀摄影作品欣赏
查看>>
Map 3D 2013 新功能和新API WebCast视频下载
查看>>
2012年7月感想
查看>>
Memcached的分布式算法-Consistent Hashing
查看>>
Spring-MVC入门(一):入门实例
查看>>
MongoDB 分片
查看>>
mvc area出现“找到多个与名为“Home”的控制器匹配的类型”错误的解决方法
查看>>
T-SQL事务编写
查看>>
Js定时执行函数方法setTimeout,clearTimeout用法及按钮addEventListener,attachEvent侦听事件...
查看>>
CGZip, a C++ wrapper for gzip methods
查看>>
使用AT指令给飞信号发短信=失败=[已经成功]
查看>>
Information Storage Management 认证题库题解系列 题21
查看>>