现在的位置: 首页 > 综合 > 正文

求集合子集问题

2013年06月15日 ⁄ 综合 ⁄ 共 564字 ⁄ 字号 评论关闭
//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

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

抱歉!评论已关闭.