The application of backtracking in recursive way

 The outputs:

C:\Users\Desktop\C++\FirstProgram> .\practice.exe
{ 0, 1, 2, 3 } 
{ 0, 1, 2 }
{ 0, 1, 3 }
{ 0, 1 }
{ 0, 2, 3 }
{ 0, 2 }
{ 0, 3 }
{ 0 }
{ 1, 2, 3 }
{ 1, 2 }
{ 1, 3 }
{ 1 }
{ 2, 3 }
{ 2 }
{ 3 }
{  } 

The corresponding codes: 

# include <iostream>
# include <iomanip>
# include <cstring>
using namespace std;
int a[] = {0,1,2,3};
int n = sizeof(a)/sizeof(a[0]);
void find_all_subsets(int layer, bool flags[]);
void display_subsets(bool flags[]);
int main()
{
    bool flags[n];
    memset(flags, 0, sizeof(flags));
    find_all_subsets(0, flags);
    return 0;
}
void find_all_subsets(int layer, bool flags[])
{
    if (layer >= n){
        display_subsets(flags);
    } else {
        flags[layer] = true;
        find_all_subsets(layer+1, flags);
        flags[layer] = false;
        find_all_subsets(layer+1, flags);
    }
}
void display_subsets(bool flags[])
{
    int flag = 0;
    cout << "{ " ;
    for (int i = 0; i < n; i++){
        if (flags[i] == true){
            if (flag == 0){
                flag ++ ;
            } else {
                cout << ", ";
            }
            cout << a[i] ;
        }
    }
    cout << " } " << endl;
}

猜你喜欢

转载自blog.csdn.net/weixin_38396940/article/details/121331372
way