AC_94. 递归实现排列型枚举

代码:

#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
//从前往后 选或者不选
int N;
vector<int>path;

void dfs(int u, int state)
{
    if (u == N)
    {
        for (auto x : path)
            cout << x << " "; 
        cout << endl;
        return;
    }
    for (int i = 0; i < N; i++)//枚举当前位置该选哪些数
    {
        if (!(state >> i & 1))
        {
            path.push_back(i + 1);//当前数放到第u个位置上
            dfs(u + 1, state | (1 << i));
            path.pop_back();//恢复现场,每次枚举之后同一分支的结果是一样的
        }
    }
}

int main()
{
    cin >> N;
    dfs(0, 0);//枚举到了第几个数  表示哪些数已经被用过了
    return 0;
}
原文地址:https://www.cnblogs.com/gcter/p/11158554.html