博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Combination Sum II
阅读量:4070 次
发布时间:2019-05-25

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

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.
  • Elements in a combination (a1a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 

跟 Combination Sum 不同的是,候选数集中的元素只能用一次,且给定的候选数集中的元素会存在重复,这样我们对其排序尽管可以保证解元素不减有序,但重复的问题就避免不了,因为我们不知道是重复的数构成的解,每个元素我们都是相同对待的。如例子中给定的,我们可以有前面的1跟 7 够成解,其实后面的 1 跟 7 也构成的了解,就要求对最终的结果去重。Combination Sum 的代码稍作修改就可以了。

class Solution {public:  /*       cur_sum: 当前的累加和       icur   : 当前候选数的下标       target :目标值       cur_re : 当前的潜在解       re     : 最终的结果集       can    : 候选数集     */   void dfs(int cur_sum, int icur, int target, vector
& cur_re, vector
> &re, vector
can) { if(cur_sum > target || icur > can.size()) return; if(cur_sum == target){ re.push_back(cur_re); return; } //(target - cur_sum >= can[i]类似剪枝,加上该判定与 //不加,时间差4-5倍。 for(int i = icur; i < can.size() && (target - cur_sum >= can[i]); ++i){ cur_sum += can[i]; cur_re.push_back(can[i]); //each item only be used once, so handle the next one. dfs(cur_sum, i + 1, target, cur_re, re, can); //go back cur_re.pop_back(); cur_sum -= can[i]; } } //why not use set? vector
> combinationSum2(vector
&num, int target) { vector
> re; vector
cur_re; if(num.size() == 0) return re; sort(num.begin(), num.end()); if(num[0] > target) return re; dfs(0, 0, target, cur_re, re, num); //erase the duplicate sort(re.begin(),re.end()); vector
>::iterator vvit; vvit=unique(re.begin(),re.end()); re.erase(vvit,re.end()); return re; } };

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

你可能感兴趣的文章
searchServer IBM OminiFind / WebSphere Commerce SOLR
查看>>
OS + Linux Disk disk lvm / disk partition / disk mount / disk io
查看>>
my read_Country
查看>>
RedHat + OS CPU、MEM、DISK
查看>>
project bbs_discuz
查看>>
net TCP/IP / TIME_WAIT / tcpip / iperf / cain
查看>>
Unix + OS books
查看>>
script webshell jspWebShell / pythonWebShell / phpWebShell
查看>>
project site_dns
查看>>
webServer kzserver/1.0.0
查看>>
hd printer lexmark / dazifuyin / dayin / fuyin
查看>>
OS + Unix IBM Aix basic / topas / nmon / filemon / vmstat / iostat / sysstat/sar
查看>>
monitorServer nagios / cacti / tivoli / zabbix / SaltStack
查看>>
my ReadMap subway / metro / map / ditie / gaotie / traffic / jiaotong
查看>>
OS + Linux DNS Server Bind
查看>>
web test flow
查看>>
web test LoadRunner SAP / java / Java Vuser / web_set_max_html_param_len
查看>>
OS + UNIX AIX command
查看>>
OS + UNIX AIX performance
查看>>
OS + UNIX AIX Tools
查看>>