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

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

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 (a1, a2, … , 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] 

 

DFS!

1 class Solution { 2 public: 3     void findNext(vector
> &res, vector
&candidates, vector
v, int sum, int target, int idx) { 4 if (sum > target || idx >= candidates.size()) { 5 return; 6 } 7 if (sum == target) { 8 res.push_back(v); 9 return;10 }11 v.push_back(candidates[idx]);12 findNext(res, candidates, v, sum + candidates[idx], target, idx);13 v.pop_back();14 findNext(res, candidates, v, sum, target, idx + 1);15 }16 17 vector
> combinationSum(vector
&candidates, int target) {18 vector
> res;19 sort(candidates.begin(), candidates.end());20 vector
v;21 findNext(res, candidates, v, 0, target, 0);22 return res;23 }24 };

 

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

你可能感兴趣的文章
中介者模式
查看>>
怎么就死循环了!
查看>>
Jmeter之tomcat性能测试+性能改进措施
查看>>
MP实战系列(七)之集成springboot
查看>>
hexo 创建文章、标签、分类的Front-matter
查看>>
Confluence 6 复杂授权或性能问题
查看>>
从中国质造到淘宝心选:CBM赋能“数造”新品牌
查看>>
Python 学习笔记1
查看>>
python(logging )日志模块学习
查看>>
树莓派 之 爬虫(Scrapy)
查看>>
.Net外包篇:我是怎么看待外包的(二)
查看>>
A* 算法发明人 Nils Nilsson 逝世
查看>>
Netty 源码阅读入门实战(三)-服务端启动
查看>>
让年轻程序员少走弯路的14个忠告(引)
查看>>
BIO NIO AIO演变
查看>>
Linux 安装 SonarQube 6.0 及Maven项目的使用
查看>>
LibreOffice 6.2.2 发布,功能强大的开源办公套件
查看>>
「架构技术专题」什么是架构设计的五个核心要素?(3)
查看>>
数据分析展现工具SDC UE
查看>>
windows下cmd时复制dos中的内容 错误信息等
查看>>