数字组合
来源:互联网 发布:directx12优化 编辑:程序博客网 时间:2024/05/16 00:33
给出一组候选数字(C)和目标数字(T),找到C中所有的组合,使找出的数字和为T。C中的数字可以无限制重复被选取。
例如,给出候选数组[2,3,6,7]和目标数字7,所求的解为:
[7],
[2,2,3]
样例
注意给出候选数组[2,3,6,7]和目标数字7
返回 [[7],[2,2,3]]
- 所有的数字(包括目标数字)均为正整数。
- 元素组合(a1, a2, … , ak)必须是非降序(ie, a1 ≤ a2 ≤ … ≤ ak)。
- 解集不能包含重复的组合。
class Solution {public: /** * @param candidates: A list of integers * @param target:An integer * @return: A list of lists of integers */ vector<vector<int> > combinationSum(vector<int> &candidates, int target) { // write your code here vector<vector<int> > result; int n = candidates.size(); if (n < 1) { return result; } sort(candidates.begin(), candidates.end()); vector<int> buf; visit(candidates, target, 0, n, buf, result); return result; }private: void visit(vector<int> &candidates, int target, int pos, int n, vector<int> &buf, vector<vector<int> > &result) { if (pos >= n) { return; } int num = target/candidates[pos]; if (num == 0) { return; } int sum = candidates[pos]*num; for (int i = 0; i < num; i++) { buf.push_back(candidates[pos]); } while (num >= 0) { if (sum == target) { result.push_back(buf); } else { visit(candidates, target-sum, pos+1, n, buf, result); } if (num > 0) { buf.pop_back(); sum -= candidates[pos]; } num--; } }};
0 0
- 组合数字
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合
- 数字组合问题
- 【其他】【RQNOJ】数字组合
- 重复数字的组合
- 数字组合歌
- Ceph radosgw 安装配置
- 三尺考研路———2015/8/26
- ub 网络框架的几种线程模型
- Permutations
- jquery 当值改变时触发方法
- 数字组合
- zoj 3885 The Exchange of Items 【最小费用最大流】
- Android文件存储
- make menuconfig出现的错误
- hdu2768
- Http Basic Authentication has some limitations, maybe nginx could do some help...
- Communication Patterns
- IOS 将类的声明,类的定义,主函数分开放的代码。
- 题目:买卖股票的最佳时机 II