求集合子集问题

//
src是源数据集合,currentIndex是在源集合里的当前下标,length为源集合的大小,dest是结果集合,num是结果集合的元素个数,初始化时,结
果集合要和源集合的个数相等.

void match( int src, int currentIndex, int length, int dest,
int num)
… {

if (currentIndex == length)

return ;


dest[num ++ ] = src[currentIndex ++ ];//采用当前元素

for ( int i = 0 ; i < num; i ++ )
… {

cout << dest[i] << “ “ ;
}

cout << endl;

match(src,currentIndex,length,dest,num);//选用当前元素进行递归

match(src,currentIndex,length,dest,num - 1 );//去除当前元素再进行递归
}

int src[] = {1,2,3};
int* dest = new int[3];打印的结果是:

1
1 2
1 2 3
1 3
2
2 3
3

所以这个算法可以求背包问,加和问题等。凡是与子集合相关的问题,全部可以用这个方法解决。

  • 本文作者: 帐前卒
  • 本文链接: http://chillyc.info/2007/1966180/
  • 版权声明: 本博客所有文章除特别声明外,只能复制超链接地址,且必须注明出处!