#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
bool IsMeasurable(int target, int weights[], int nWeights);
void SwapArray(int weights[], int i, int j);
int main()
{
int sampleWeights[] = { 1, 3 };
int nSampleWeights = 2;
cout << boolalpha;
cout << IsMeasurable(2, sampleWeights, nSampleWeights) << endl;
cout << IsMeasurable(5, sampleWeights, nSampleWeights) << endl;
return 0;
}
bool IsMeasurable(int target, int weights[], int nWeights)
{
// simple case
if (target == 0 && nWeights == 0) {
return true;
}
if ((target == 0 && nWeights != 0) ||
(target != 0 && nWeights == 0)) {
return false;
}
// recursive decomposition
for (int i = 0; i < nWeights; i++) {
int weight = weights[i];
SwapArray(weights, i, nWeights-1);
if (IsMeasurable(target-weight, weights, nWeights-1) ||
IsMeasurable(target, weights, nWeights-1) ||
IsMeasurable(target + weight, weights,nWeights-1)) {
return true;
}
SwapArray(weights, i, nWeights-1);
}
return false;
}
void SwapArray(int weights[], int i, int j) {
int temp = weights[i];
weights[i] = weights[j];
weights[j] = temp;
}