Combination Sum
2016-01-19 22:20
295 查看
每日算法——leetcode系列
问题 Combination Sum
Difficulty: MediumGiven 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,7and target
7,
A solution set is:
[7] [2, 2, 3]
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { } };
翻译
和的组合
难度系数:中等给定一个一些数组成的候选集合C,和一个目标数T。现从C中选出一些数,求所有不同的取数方案使其累加和恰好等于T。
C中的每个数都可以取若干次。
注意
所有的数(包括目标数)都为正整数
组合中的元素(a1, a2, … , ak) 不能为降序排列。(ie, a1 ≤ a2 >≤ … ≤ ak)
不能有重复的组合方案
例如:候选集合
2,3,6,7和目标值
7,
答案为:
[7] [2, 2, 3]
思路
此题有点像是钱的面值为1、5、10,然后用这些面值的钱组合成一个特定的数。不考虑加和加起来大于Int_Max的情况。
由于每个数可以重复,可于抽象成树,root结节点有候选集合的总个数个子节点,其中每个子节点的子节点是子节点本身,重复下去。
以候选集合
2,3,6,7为例
root节点往下,有节点
2,3,6,7,从左取
2这个节点push进
vector<int>,每push一次将目标值减去取的节点值,如果剩余的值大于0,继续取,按深度优先取,
2的子节点还是
2,···
还是画图比较清晰,找到好的画圈工具再加上
代码
class Solution { public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { sort(candidates.begin(),candidates.end()); len = static_cast<int>(candidates.size()); temAndidates = candidates; vector<int> combination; dfs(combination, target, 0); return result; } private: int len; vector<int> temAndidates; vector<vector<int> > result; void dfs(vector<int>& combination, int remainder, int tempLen){ if (tempLen >= len) { return; } if (remainder == 0){ result.push_back(combination); return; } else { for (int i = tempLen; i < len; ++i) { if (remainder < temAndidates[i]){ return; } combination.push_back(temAndidates[i]); dfs(combination, remainder - temAndidates[i], i); combination.pop_back(); } } } };
相关文章推荐
- HDFS为分布式搭建
- 页面元素用JS动态添加的有效事件绑定方式
- JAVA多线程学习之ReentrantReadWriteLock
- 4.DTD - 元素 - 属性
- 写代码过程中一些数字推理公式
- VNC
- CTEX安装中的一个问题的解决
- crtmpserver的一个bug
- div和span的区别
- 1.1.2. 了解JVM各种参数及调优
- 位图排序
- sortStringText
- bloc简介
- 笔记:《高效能人士的七个习惯》第九章 习惯六 统合综效——创造性合作的原则
- 【NYOJ】[33]蛇形填数
- 0919学习笔记
- 面试经历---UC(2016年01月11日下午面试)
- Python定制容器
- Android开发之View动画效果插补器Interpolator
- Java 开源软件测试工具