您的位置:首页 > 其它

recursion problem(IsMeasurable)(Is this correct?)

2015-05-31 21:12 295 查看
#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;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: