当前位置:网站首页>Recursive implementation of exponential, permutation and combination enumerations

Recursive implementation of exponential, permutation and combination enumerations

2022-06-12 05:45:00 Python's path to becoming a God

Exponential type

#include <iostream>

using namespace std;

const int N = 15;
int st[N],num[N];
int n;
void dfs(int u)
{ 
    
     if(u > n)
     { 
    
         for(int i = 1;i <= n ;i ++)
         { 
    
             if(st[i] == 1)
             cout <<i<<" ";
         }
         cout <<endl;
     }
     else
     { 
    
         st[u] = 2;
         dfs(u+1);
         //st[u] = 0;
         st[u] = 1;
         dfs(u+1);
         //st[u] =0 ;
     }
}
int main()
{ 
    
    cin >> n;
    dfs(1);
    
    return 0;
}

Permutation type

#include <iostream>

using namespace std;

const int N = 12;

int n;
bool st[N];
int num[N];
void dfs(int u)
{ 
    
    if(u > n)
    { 
    
        for(int i = 1;i <= n;i ++)
        { 
    
            cout <<num[i]<<" ";
        }
        cout <<endl;
    }
    else
    { 
    
        for(int i = 1;i <= n;i ++)
        { 
    
            if(st[i] == false)
            { 
    
                st[i] = true;
                num[u] = i;
                dfs(u+1);
                st[i] = false;
            }
        }
    }
}
int main()
{ 
    
    cin >> n;
    dfs(1);
    
    return 0;
}

Combination

#include <iostream>

using namespace std;

const int N = 110;
bool st[N];
int num[N];
int n,m;
void dfs(int u,int start)
{ 
    
    if(u > m)
    { 
    
        for(int i = 1;i <= m;i ++)
        { 
    
            cout << num[i]<<" ";
        }
        cout <<endl;
    }
    else
    { 
    
        for(int i = start ;i <= n;i ++) //for Loop here is to arrange enumerations differently 
        { 
    
            if(st[i] == false)
            { 
    
                st[i] = true;
                num[u] = i;
                dfs(u+1,i+1);
                st[i] = false;
            }
        }
    }
}
int main()
{ 
    
    cin >> n>> m;
    dfs(1,1);
    
    return 0;
}

原网站

版权声明
本文为[Python's path to becoming a God]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203010613198314.html