【leetcode】Combination Sum

【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;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值