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

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

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

The same repeated number may be chosen from C unlimited number of times.

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 2,3,6,7 and target 7
A solution set is: 
[7] 
[2, 2, 3] 

给定一组候选解集合,以及一个目标值,给出所有能够累加得到该目标值的组合,候选解元素可以重复使用任意次。

题目要求解的形式要按非降序,那就开始之前将候选序列排个序。

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){ //cur_re.push_back(cur_sum); 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]); dfs(cur_sum, i, target, cur_re, re, can); //go back cur_re.pop_back(); cur_sum -= can[i]; } } vector
> combinationSum(vector
&candidates, int target) { vector
> re; vector
cur_re; if(candidates.size() == 0) return re; sort(candidates.begin(), candidates.end()); if(candidates[0] > target) return re; dfs(0, 0, target, cur_re, re, candidates); return re; }};

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

你可能感兴趣的文章
星环后台研发实习面经
查看>>
大数相乘不能用自带大数类型
查看>>
字节跳动后端开发一面
查看>>
CentOS Tensorflow 基础环境配置
查看>>
centOS7安装FTP
查看>>
FTP的命令
查看>>
CentOS操作系统下安装yum的方法
查看>>
ping 报name or service not known
查看>>
FTP 常见问题
查看>>
zookeeper单机集群安装
查看>>
do_generic_file_read()函数
查看>>
Python学习笔记之数据类型
查看>>
Python学习笔记之特点
查看>>
Python学习笔记之安装
查看>>
shell 快捷键
查看>>
VIM滚屏操作
查看>>
EMC 2014存储布局及十大新技术要点
查看>>
linux内核内存管理(zone_dma zone_normal zone_highmem)
查看>>
将file文件内容转成字符串
查看>>
循环队列---数据结构和算法
查看>>