子集和实现

时间:2012-06-28 12:23:02

标签: c++ c algorithm

我正在实现子集求和的算法:

SUBSET SUM(X[1 .. n], T ):
if T = 0
return T RUE
else if T < 0 or n = 0
return FALSE
else
return SUBSET SUM(X[2 .. n], T ) ∨ SUBSET SUM(X[2 .. n], T − X[1])

请帮我解释如何在递归时传递简化数组X [2 ... n]?

这是我编写的代码,它会导致分段错误:

#include <stdio.h>

    int subsetsum(int a[], int sum, int size)
    {
            if(sum==0)
            return 1;
            else if (sum<0 || size <0)
            return  0;
            else
            return (subsetsum(a+1 , sum, size-1) || subsetsum(a+1, sum - *a, size-1));
    }
    `

    int main(int argc, char **argv)
    {
            int a[]={2,4,1,3,5},x;
            x=subsetsum(a,6,5);
            printf("%d",x);
            return 0;
    }

2 个答案:

答案 0 :(得分:2)

template<class It>
void recurse(It begin, It end)
{
   ... recurse(begin+1, end) ...
}

答案 1 :(得分:1)

当用作函数的参数时,C / C ++中的数组被隐式地衰减为指向数组的原始内存缓冲区的指针。因此,为了传递X[2...n],您只需通过1递增数组指针参数。例如,您可以执行以下操作:

bool subset_sum(const int* array, const int array_size, int* sum)
{
    //...your code for the rest of the algorithm

    subset_sum(array+1, array_size, sum) //one of the recursive calls
}

在下一次递归调用中传递参数array+1会将数组指针递增1,并使用指向数组X[1...n]的指针,然后使其指向数组X[2...n] 。您可以使用array_size参数来检测数组的结尾。

最后,您可以这样致电subset_sum

int array_numbers = {1, 2, 3, 4, 5, 6, 7};
int sum = 0;

subset_sum(array_numbers, sizeof(array_numbers)/sizeof(int), &sum);
相关问题