【leetcode】Combination Sum
2015-04-24 21:39
465 查看
还是一道回溯题,趁热打铁吧算是,题目我就不解读了。重点还是几个:退出条件、状态查询、状态记录、记录回滚、递归尝试(好吧,我每次都会说得不一样,但是回溯就这几点,特别容易出错的是状态不满足时的记录回滚)。代码其实写得挺丑的,我是从后往前遍历,这样可以省去一些“从前往后遍历时不必要的尝试”,但是leetcode总是说我错误,其实错在排序上,所以我用了很笨的方法,一维数组每次加入到二维数组中排序一次,最后对二维数组也排序一次(这里应该会很浪费时间)。上代码伺候:
class Solution { private: vector<int> tmp; vector<vector<int> > res; public: void solve(int depth,vector<int> &candidates,int target) { if(target<0) { return; } else if(target==0) { tmp.push_back(candidates[depth]); vector<int> tt(tmp); sort(tmp.begin(),tmp.end()); res.push_back(tmp); tmp=tt; tmp.erase(tmp.end()-1,tmp.end()); return; } else { tmp.push_back(candidates[depth]); for(int i=depth;i>=0;--i) { solve(i,candidates,target-candidates[i]); } tmp.erase(tmp.end()-1,tmp.end()); } } vector<vector<int> > combinationSum(vector<int> &candidates, int target) { res.clear(); for(int depth=candidates.size()-1;depth>=0;--depth) { tmp.clear(); solve(depth,candidates,target-candidates[depth]); } sort(res.begin(),res.end()); return res; } };
相关文章推荐
- [LeetCode]Combination Sum
- Combination Sum--LeetCode
- [LeetCode]Combination Sum
- [LeetCode] Combination Sum
- 【数据结构与算法】【leetcode】sum2 sum3 sum4 Combination Sum
- LeetCode(39) Combination Sum
- Leetcode - Combination Sum
- leetcode-Combination Sum
- leetcode 39 Combination Sum (回溯法)
- [LeetCode]39 Combination Sum
- LeetCode_Combination Sum
- Combination Sum 组合数求和-Leetcode
- *LeetCode-Combination Sum
- Java for LeetCode 039 Combination Sum
- LeetCode——Combination Sum
- leetcode: Combination Sum
- LeetCode(39)--Combination Sum
- LeetCode: Combination Sum
- LeetCode39 Combination Sum
- LeetCode: Combination Sum 解题报告