LeetCode 39. 组合总和 c++

采用回溯法

class Solution {
public:
	vector> combinationSum(vector& candidates, int target) {
		vector> res;
		if (candidates.size() == 0 || target < 0){
			return res;
		}
		vector  curr;
		sort(candidates.begin(), candidates.end());//进行排序
		BackTracking(res, curr, candidates, target, 0);
		return res;
	}
	void BackTracking(vector>& res, vector curr, vector candidates, int target, int level){
		if (target == 0){
			res.push_back(curr);
			return;
		}
		else if (target < 0){
			return;
		}
		for (int i = level; i < candidates.size(); i++){
			target -= candidates[i];
			curr.push_back(candidates[i]);
			BackTracking(res,curr,candidates,target,i);
			curr.pop_back();
			target += candidates[i];
		}
	}
};

 

你可能感兴趣的:(Leetcode)