LeetCode 39. 組合せ合計c++

862 ワード

遡及法を採用する
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];
		}
	}
};