题目要求:Combination Sum

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]

代码如下:

class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
sort(candidates.begin(), candidates.end());
vector<int>::iterator pos = unique(candidates.begin(), candidates.end());
candidates.erase(pos, candidates.end()); vector<vector<int> > ans;
vector<int> record;
searchAns(ans, record, candidates, target, 0);
return ans;
} private:
void searchAns(vector<vector<int> > &ans, vector<int> &record, vector<int> &candidates, int target, int idx) { if (target == 0) {
ans.push_back(record);
return;
} if (idx == candidates.size() || candidates[idx] > target) {
return;
} for (int i = target / candidates[idx]; i >= 0; i--) {
record.push_back(candidates[idx]);
} for (int i = target / candidates[idx]; i >= 0; i--) {
record.pop_back();
searchAns(ans, record, candidates, target - i * candidates[idx], idx + 1);
}
}
};

最新文章

  1. 便于开发的Helper类
  2. Java中的一个类怎么调用另一个类中的方法
  3. 【Unity】Update()和FixedUpdate()
  4. sed学习笔记
  5. WCF 发布使用
  6. js 运算符优先级
  7. Android Studio 设置不自动缩进匿名内部类
  8. C#删除微信自定义菜单
  9. 【转】Java 枚举7常见种用法
  10. Memcached源码分析之items.c
  11. Android开发技巧——定制仿微信图片裁剪控件
  12. STM32基于固件库新建MDK工程模板(精简版)
  13. net-tools与iproute2
  14. 二、两条Linux删除数据跑路命令
  15. 3. Spring 核心之 IOC(控制反转) &amp; DI(依赖注入)
  16. Linux之nginx服务
  17. shell 生成MAC地址
  18. Java中单例设计模式,饿汉式和懒汉式
  19. &lt;转载&gt;apache 配置 http://www.blogjava.net/bukebushuo/articles/229103.html
  20. Flash网页小游戏开发教程

热门文章

  1. TCP/IP 基础知识
  2. python机器学习的开发流程
  3. 我的 Redis 被入侵了
  4. java常用类——包装类
  5. (模板)graham扫描法、andrew算法求凸包
  6. 【Luogu】P1072 Hankson 的趣味题 题解
  7. System.Net邮件发送功能踩过的坑
  8. leetcode131:letter-combinations-of-a-phone-number
  9. 新疆地形数据下载:30米、12.5米、5米DEM地形数据
  10. LSV又新增13个地质图!量测对比分析全都能搞定