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

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

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]

class Solution {public:    vector
> ans; vector
> combinationSum2(vector
&num, int target){ /** 10,1,2,7,6,1,5 and target 8, [1, 7] [1, 2, 5] [2, 6] [1, 1, 6] Each number in C may only be used once in the combination. */ vector
path; ans.clear(); if (num.size() == 0){ return ans; } //sort vector
> num_counter; sort(num.begin(),num.end()); int counter = 1; for(int i = 1; i < num.size(); i++){ if (num[i] == num[i -1]){ counter++; }else{ num_counter.push_back(make_pair(num[i-1],counter)); counter = 1; } } num_counter.push_back(make_pair(num[num.size() -1],counter)); dfs(num_counter,path,target); return ans; } void dfs(vector
> & candidates, vector
& path,int target){ if (target == 0){ ans.push_back(path); return; } if (target < 0){ return; } int j = 0; for(;j < candidates.size();j++){ if (path.empty()){ break; } if (candidates[j].first == path[path.size() -1]){ int c = 0; for(int m = 0; m < path.size(); m++){ if (path[m] == candidates[j].first){ c++; } } if (c < candidates[j].second){ break; } }else if (candidates[j].first > path[path.size() -1]){ break; } } for(int i = j; i < candidates.size() && target - candidates[i].first >= 0; i++){ //candidates 事先排好序 path.resize(path.size() + 1); path[path.size() -1] = candidates[i].first; dfs(candidates,path,target - candidates[i].first); path.resize(path.size() - 1); } }};using namespace std;int main(int argc, char *argv[]) { int a[] = { 1,2,1,5,1,4,6,7}; vector
v(a,a+8); vector
> ans; Solution sol; ans = sol.combinationSum2(v,7); for(int i = 0; i < ans.size(); i++){ for(int j = 0; j < ans[i].size(); j++){ cout<<" " << ans[i][j]; } cout << endl; }}

 

转载于:https://www.cnblogs.com/kwill/p/3162047.html

你可能感兴趣的文章
iOS 数组排序
查看>>
第三节
查看>>
PHP结合MYSQL记录结果分页呈现(比较实用)
查看>>
Mysql支持的数据类型
查看>>
openSuse beginner
查看>>
Codeforces 620E(线段树+dfs序+状态压缩)
查看>>
Windows7中双击py文件运行程序
查看>>
Market entry case
查看>>
bzoj1230 开关灯 线段树
查看>>
LinearLayout
查看>>
学习python:day1
查看>>
css3动画属性
查看>>
第九次团队作业-测试报告与用户使用手册
查看>>
Equal Sides Of An Array
查看>>
CentOS笔记-用户和用户组管理
查看>>
Mongodb 基本命令
查看>>
Qt中QTableView中加入Check列实现
查看>>
“富豪相亲大会”究竟迷失了什么?
查看>>
控制文件的备份与恢复
查看>>
返回代码hdu 2054 A==B?
查看>>