[leetcode] 39. Combination Sum 解题报告
2015-12-21 08:41
274 查看
题目链接:https://leetcode.com/problems/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
A solution set is:
思路:深搜。为保证结果有序,需要将vector首先排序,然后搜索的时候只能搜索本身或者比他大的数。思路比较清晰。写的时候还是忘记首先排序,以为他给的数据就是有序的,好坑!
代码如下:
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,7and target
7,
A solution set is:
[7]
[2, 2, 3]
思路:深搜。为保证结果有序,需要将vector首先排序,然后搜索的时候只能搜索本身或者比他大的数。思路比较清晰。写的时候还是忘记首先排序,以为他给的数据就是有序的,好坑!
代码如下:
class Solution { public: void DFS(vector<int>& candidates, int target, vector<int> vec, int sum, int index) { if(sum == target) return result.push_back(vec); if(index >= candidates.size() || sum > target) return; DFS(candidates, target, vec, sum, index+1); vec.push_back(candidates[index]); DFS(candidates, target, vec, sum+candidates[index], index); } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { if(candidates.size() ==0) return result; sort(candidates.begin(), candidates.end()); DFS(candidates, target, vector<int>(), 0, 0); return result; } private: vector<vector<int>> result; };
相关文章推荐
- 常见报错信息
- 使用必应查询接口开发搜索工具:反查一个IP上的旁站
- Codeforces 437A The Child and Homework
- audio-音频标签
- video-视频标签
- 零基础自学Python两个月小结
- win7系统重装后重启无法开机出现grub或者是出现红屏的解决方案
- MySQL 部分函数使用
- android 录音笔demo!!!(Baseadapter、file、MediaRecorder、AlertDialog)
- UWP开发:APP之间的数据交互(以微信为例)
- 动态设置titleBar的高度
- 流氓的win10,无法禁止的升级(私底下不知道在干嘛)
- POI:数据批量导出、按模板导出
- linux文件打开模式
- MongoVUE
- HTML5基础/简介
- 2015-03-13---抽象工厂(附代码),
- 开源协议
- 工厂方法
- DELPHI7加载UNICODE编码格式的TXT显示为乱码的解决方法