回溯法之子集树

回溯法之子集树(0,1背包)

当所给问题是从n个元素的集合S中找出满足某种性质的子集时,解空间为子集树。例如:0-1背包问题

回溯法搜索子集树算法描述为:
 
void backtrack(int  t)
 
{
     if(t>n)   
        output(x);
     else
        for(int i=0; i<=1; i++) //注意,这里的0,1 是X[i]的取值范围,t表示层数
      {  
             x[t] = i; 
             if(constraint(t) && bound(t))     
                  backtrack(t+1);
       }  
}


子集树实例

//打印出vector的所有子集
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

void printVector(vector<int> array );

void dfs(vector<int>& array, int dep)
{
    int size =  array.size();

    if(dep == size)
    {
        printVector(array);
        return;
    }
    //dfs to the next level
    //i的取值为0,1
    for(int i = 0; i < 2; i++)
    {
        array[dep] = i;
        dfs(array, dep+1);
    }

}


void printVector(vector<int> array )
{
    for(int i = 0; i <array.size(); i++)
        cout << array[i]<< "\t" ;
    cout << endl;
}

int main()
{
    vector<int> b ;
    //为b重新定义大小,5,并且初值为0
    b.resize(5, 0);
    dfs(b, 0);
    return 0;
}

打印结果:

0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 0 1 1
0 0 1 0 0
0 0 1 0 1
0 0 1 1 0
0 0 1 1 1
0 1 0 0 0
0 1 0 0 1
0 1 0 1 0
0 1 0 1 1
0 1 1 0 0
0 1 1 0 1
0 1 1 1 0
0 1 1 1 1
1 0 0 0 0
1 0 0 0 1
1 0 0 1 0
1 0 0 1 1
1 0 1 0 0
1 0 1 0 1
1 0 1 1 0
1 0 1 1 1
1 1 0 0 0
1 1 0 0 1
1 1 0 1 0
1 1 0 1 1
1 1 1 0 0
1 1 1 0 1
1 1 1 1 0
1 1 1 1 1

但这适用于集合比较小的情况



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值