solution.cpp 628 字节
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
	vector<vector<int>> combinationSum(vector<int> &candidates, int target)
	{
		vector<vector<int>> res;
		dfs(candidates, 0, target, res);
		return res;
	}
private:
	vector<int> stack;
	void dfs(vector<int> &candidates, int start, int target, vector<vector<int>> &res)
	{
		if (target < 0)
		{
			return;
		}
		else if (target == 0)
		{
			res.push_back(stack);
		}
		else
		{
			for (int i = start; i < candidates.size(); i++)
			{
				stack.push_back(candidates[i]);
				dfs(candidates, i, target - candidates[i], res);
				stack.pop_back();
			}
		}
	}
};