zoukankan      html  css  js  c++  java
  • Combination Sum

    class Solution {
    private:
    	vector<int> c;
    	vector<vector<int> > res;  //保存最后结果
    public:
    	vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
    		vector<int> a;
    		sort(candidates.begin(), candidates.end()); //先对C中候选数升序排序,为后面的剪枝做准备
    		c = candidates;
    		backtrack(a, 0, target);
    		//for(vector<int> &m:res)
    	    //sort(m.begin(), m.end());
    		//res.erase(unique(res.begin(), res.end()), res.end());
    		return res;
    	}
    	int sum(vector<int>& a){
    		int res = 0;
    		for (int i = 0; i<a.size(); i++){
    			res += a[i];
    		}
    		return res;
    	};
    	void backtrack(vector<int>& a, int k, int target)
    	{
    		if (k == c.size()) return;
    		if (sum(a) == target){
    			res.push_back(a);
    			return;
    		}
    		else if (sum(a)>target)
    			return;
    		else {
    			//k = k + 1;
    			for (int i = k; i<c.size(); i++) {
    				//a[k] = c[i];
    				a.push_back(c[i]);
    				backtrack(a, i, target);
    				a.pop_back();
    
    			}
    		}
    	}
    };

  • 相关阅读:
    tcpdump 筛选抓包
    TCP拥塞避免
    【转载】TCP协议
    go 参数传递的是值还是引用 (转)
    go 数组指针 指针数组
    go 协程
    go 接口实现
    go函数可见性
    go 继承
    go 结构体函数
  • 原文地址:https://www.cnblogs.com/muyangshaonian/p/9650496.html
Copyright © 2011-2022 走看看