输入一个整形数组 和一个目标数字。要求打印出所有用给定数组内的数字的和等于给定目标数字的组合,给定数组内的每个数字使用次数不限。如输入数组{2, 3},目标数字12,。则应打印出:{3, 3, 3, 3}, {3, 3, 2, 2, 2}, {2, 2, 2, 2, 2, 2}。
#include <iostream>
#include <string>
#include <map>
#include <vector>
using namespace std;
void fun(int a[], int n, int &pos, int &value, int target, vector<int> &buf, map<int,int> locs)
{
if (value == target)
{
for (int i = 0; i < buf.size(); i++)
{
cout << buf[i] << " ";
}
cout << endl;
}
if (pos >= 0 && value < target)
{
buf.push_back(a[pos]);
value += a[pos];
fun(a, n, pos, value, target, buf, locs);
}
else
{
if (buf[0] == a[0])
{
return;
}
while (buf[buf.size()-1] == a[0])
{
value -= buf[buf.size()-1];
buf.pop_back();
}
pos = locs[buf[buf.size()-1]] - 1;
value -= buf[buf.size()-1];
buf.pop_back();
fun(a, n, pos, value, target, buf, locs);
}
}
int main()
{
int a[] = {2,3};
int value = 0;
int target = 12;
vector<int> buf;
map<int,int> locs;
int n = sizeof(a)/sizeof(a[0]);
int pos = n-1;
for (int i = 0; i < n; i++)
{
locs[a[i]] = i;
}
fun(a, n, pos, value, target, buf, locs);
return 0;
}