思路:遍历所有的组合,判断每一种组合的值是否满足条件。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void visit(vector<int> &arr, int pos, int n, int sum, int target, vector<int> &buf) {
if (pos == n) {
return;
}
if (arr[pos] > 0 && sum + arr[pos] > target) {
return;
}
buf.push_back(arr[pos]);
if (sum + arr[pos] == target) {
for (auto a : buf) {
cout << a << " ";
}
cout << endl;
}
visit(arr, pos + 1, n, sum + arr[pos], target, buf);
buf.pop_back();
visit(arr, pos + 1, n, sum, target, buf);
}
void fun(vector<int> &arr, int n, int target) {
sort(arr.begin(), arr.end());
vector<int> buf;
visit(arr, 0, arr.size(), 0, target, buf);
}
int main() {
vector<int> arr = {1, 2, 3, 4, 7, 8, 9, 10};
fun(arr, arr.size(), 15);
return 0;
}