首页 技术 正文
技术 2022年11月16日
0 收藏 947 点赞 4,392 浏览 1256 个字

前言

 

【LeetCode 题解】系列传送门:  http://www.cnblogs.com/double-win/category/573499.html

 

1.题目描述

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, a1a2 ≤ … ≤ 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]

2. 题意

给定一个候选集合,集合中的元素以非递减方式存放。给定一个目标值T

输出所有唯一的组合。

3. 思路

由于不能出现重复元组,所以我们先将candidate set进行排序,然后规定比新插入的元素不能比当前元素小。

采用DFS思想即可。

4: 解法

class Solution {
private:
vector<int> ans;
vector<vector<int> > ret;
public:
void DFS(int start,vector<int> &candidates, int target){
if(target==0){
ret.push_back(ans);
return;
} for(int i=start;i<candidates.size();++i){
if(target <candidates[i]) return;
ans.push_back(candidates[i]);
DFS(i,candidates,target-candidates[i]);
ans.pop_back();
}
}
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
ans.clear();
ret.clear();
if(!target || !candidates.size()) return ret;
sort(candidates.begin(),candidates.end());
DFS(0,candidates,target);
return ret;
}
};

 

[LeetCode 题解] Combination Sum

作者:Double_Win

出处: http://www.cnblogs.com/double-win/p/3896010.html 

声明: 由于本人水平有限,文章在表述和代码方面如有不妥之处,欢迎批评指正~

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,580
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918