回溯法(leetcode-Combination Sum)
程序员文章站
2022-05-21 22:32:43
...
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7]
and target 7
,
A solution set is:
[ [7], [2, 2, 3] ]本题宜采用回溯法,代码如下:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
void backTracking(vector<vector<int>> &res, vector<int> arr ,vector<int>candidate ,int start,int target )
{
if (target == 0)//满足条件,输出结果
{
res.push_back(arr);
return;
}
for (int i = start; i < candidate.size(); i++)//枚举所有可能的路径
{
if (candidate[i] <= target)//满足界限函数和约束条件
{
arr.push_back(candidate[i]);
backTracking(res, arr, candidate, i, target - candidate[i]);
arr.pop_back();//回溯清理工作
}
}
}
int main()
{
vector<int> candidate = { 2, 3, 6, 7 };
int target = 7;
vector<vector<int>> res;
vector<int> arr;
sort(candidate.begin(), candidate.end());
backTracking(res, arr, candidate, 0, target);
for (int i = 0; i < res.size(); i++)
{
for (int j = 0; j < res[i].size(); j++)
{
cout << res[i][j] << " ";
}
cout << endl;
}
return 0;
}