LeetCode(39) Combination Sum
2015-07-22 17:11
351 查看
将解决这个问题的整个过程记录下来:
1、首先我以[2,3,6,7,9] 9为例研究了一下可行解,在小规模情况下目测可行解为
[[9], [2,7],[3,6]],我就想如何按照某种规则来搜索出这些可行解呢,此时我想到用于找零问题的贪婪算法,将可行解集合按照贪婪算法重新整理为,[9],[7,2],[6,3]。
2、此时开始想到排列树,编程之美3.2节,发现在排列树上进行贪婪算法是可行的。
3、接下来就是实现算法了,开始写深度优先搜索代码。
4、摸索性的写,后来慢慢发现应该再定义一个函数,而现在写的地方属于驱动函数的部分。
5、开始写用于递归的函数
6、用小规模例子试运行,修正程序的不精确地方(打磨)
7、成功。
1、首先我以[2,3,6,7,9] 9为例研究了一下可行解,在小规模情况下目测可行解为
[[9], [2,7],[3,6]],我就想如何按照某种规则来搜索出这些可行解呢,此时我想到用于找零问题的贪婪算法,将可行解集合按照贪婪算法重新整理为,[9],[7,2],[6,3]。
2、此时开始想到排列树,编程之美3.2节,发现在排列树上进行贪婪算法是可行的。
3、接下来就是实现算法了,开始写深度优先搜索代码。
4、摸索性的写,后来慢慢发现应该再定义一个函数,而现在写的地方属于驱动函数的部分。
5、开始写用于递归的函数
6、用小规模例子试运行,修正程序的不精确地方(打磨)
7、成功。
[code]class Solution { public: void dfsSearch(vector<int> &candidates, int serialNumber, vector<int> &combinationIndex, int depth, int target, vector<vector<int>> &result) { for(int i = serialNumber; i < candidates.size(); i++) { combinationIndex[depth] = i; if(target - candidates[i] > 0) dfsSearch(candidates, i, combinationIndex, depth + 1, target - candidates[i], result); if(target - candidates[i] == 0) { vector<int> tmp; for(int j = 0; j <= depth; j++) tmp.push_back(candidates[combinationIndex[j]]); reverse(tmp.begin(), tmp.end()); result.push_back(tmp); continue; } if(target - candidates[i] < 0) continue; } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); reverse(candidates.begin(), candidates.end()); vector<vector<int>> result; int depth = 0; vector<int> combinationIndex(1000, -1); int serialNumber = 0; dfsSearch(candidates, serialNumber, combinationIndex, depth, target, result); reverse(result.begin(), result.end()); return result; } };
相关文章推荐
- 堆排序实现
- [Elasticsearch] 过滤查询以及聚合(Filtering Queries and Aggregations) 5
- ab压nginx集群失败率的问题
- 基于CentOS的MySQL学习补充三--使用Shell批量创建数据库表
- 自定义控件入门学习之Helloworld
- python setDaemon
- HDU 1555 How many days?
- 《excel2007视频教程》 学习笔记一 基础
- Android的NDK开发(2)——利用Android NDK编写一个简单的HelloWorld
- Android的NDK开发(2)——利用Android NDK编写一个简单的HelloWorld
- TortoiseSVN使用简介
- XPOSED源码研究之XposedInstaller(5)ModulesFragment
- XPOSED源码研究之XposedInstaller(4)InstallerFragment
- 《深入浅出struts2》--第四章,OGNL
- 不想做攻城狮的程序猿不是好同学
- Python网络编程(Socket)
- [Elasticsearch] 聚合作用域(Scoping Aggregations) 4
- [002] 微信公众帐号开发教程第2篇-微信公众帐号的类型(普通和会议)
- ViewPager禁止左右滑动
- Json是什么时候开始的,Json起源,Json历史