samedi 27 juin 2015

subset sum recursive solution producing incorrect output

Followed this method (pdf) to implement a recursive solution, but I think it is buggy. I have exactly implemented it as described in the pdf file.

The output of the code below is wrong. It shows the target locations. The target array contains bit representation of the numbers that should be added to get the sum.

Placing the binary[i] = 1 in else if condition fixes the problem, but it doesn’t make sense. Is it possible to clarify what is the right solution?

#define SIZE(a) sizeof(a)/sizeof(a[0])
int binary[100];
void foo(int target, int i, int sum, int *a, int size) {
    binary[i] = 1;
    if (target == sum+a[i]) {
        int j;
        for (j=0;j<size;j++)
            printf("%d\n", binary[j]);
        return;
    } else if ((i+1 < size) && (sum + a[i] < target)) {
        foo(target, i+1, sum + a[i], a, size);
    }
    if ((i+1 < size) && (sum +a[i+1] <= target)) {
        binary[i] = 0;
        foo(target, i+1, sum, a, size);
    }
}

int main()
{
    int i, target =10,a[] = {1, 2, 3, 5, 100};
    foo(target, 0, 0, a, SIZE(a));
}

Current output: 0 1 1 1 1 Expected output: 0 1 1 1 0

Aucun commentaire:

Enregistrer un commentaire