您的位置:首页 > 其它

【leetcode】Combination Sum

2015-04-24 21:39 465 查看


【leetcode】Combination Sum



还是一道回溯题,趁热打铁吧算是,题目我就不解读了。重点还是几个:退出条件、状态查询、状态记录、记录回滚、递归尝试(好吧,我每次都会说得不一样,但是回溯就这几点,特别容易出错的是状态不满足时的记录回滚)。代码其实写得挺丑的,我是从后往前遍历,这样可以省去一些“从前往后遍历时不必要的尝试”,但是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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: