Combination Sum

Given a set of candidate numbers (C) (without duplicates) 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.
  • 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的思想来解题。

数组从头到尾,每次决定是否将当前的值加入组合:

  • 如果是,那么判断当前组合是否sum == target,

    • 等于——>将该组合加入解集合,return;
    • 不等于——>继续递归
  • 如果不是,那么index+1(数组向后移动),继续递归

代码非常容易理解,如下所示:

class Solution {
public:
vector<vector<int>> re;
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int> temp;
search(candidates,temp,0,candidates.size(),target,0);
return re;
}
void search(vector<int> candidates,vector<int> temp,int index,int len,int target,int cur){ if(index >= len || cur > target) return; //do not select this value,search deepper,index need increase
search(candidates,temp,index+1,len,target,cur); /*
* select this value,and judge if it equals the target.
* If yes,push back the vector and return,if not,search continue
* index don't change,because the number can be repeated
*/
temp.push_back(candidates[index]);
cur += candidates[index];
if(cur == target){
re.push_back(temp);
return;
}
else{
search(candidates,temp,index,len,target,cur);
}
}
};

最新文章

  1. swfit-学习笔记(数组的使用)
  2. JUnit4 中@AfterClass @BeforeClass @after @before的区别对比
  3. 一个C++宏定义与枚举定义重复的编译错误
  4. C#中的数组,多维数组和交错数组
  5. cannot use the same dataset for report.dataset and page.dataset
  6. Fortran并行计算的一些例子
  7. Linux 消息队列编程
  8. #tensorflow入门(1)
  9. sp_getAppLock使用
  10. PostGIS导出SHP中文乱码
  11. DOM4j 修改和删除
  12. vue 获取当前时间
  13. UVA816-Abbott&#39;s Revenge(搜索进阶)
  14. js控制json生成菜单——自制菜单(一)
  15. scanf的拓展用法——匹配特定字符
  16. MySQL闪退问题的解决
  17. sgu 122. The book 满足ore性质的汉密尔顿回路 难度:2
  18. I.MX6 ethtool 移植
  19. 数据段描述符和代码段描述符(二)——《x86汇编语言:从实模式到保护模式》读书笔记11
  20. js 跳转整理

热门文章

  1. 【文文殿下】[BZOJ3277] 串
  2. android 开发 简单的小计算器
  3. hadoop1.0.4运行程序出现“Java heap Space”错误
  4. mysql 多实例
  5. 各大浏览器相继发布声明将停止支持 TLS 1.0 和 TLS 1.1 !
  6. Centos7.4下安装Nginx
  7. Description &amp;&amp;debugDescription &amp;&amp; runtime(debug模式下调试model)
  8. Vijos 小胖的奇偶
  9. 接口测试-postman,JMeter与LoadRunner比较
  10. Django分页类的封装