Files
python/C++专题课程/全排列/ShjCppStudy/DFS实现全排列.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

39 lines
852 B
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include<bits/stdc++.h>
using namespace std;
int a[10], book[10], n;
//全排列算法,运用深度优先搜索dfs
void dfs(int step)
{
int i;
if (step == n + 1) //如果站在第n+1个箱子前,则表示前n个箱子已经排列好
{
for (i = 1; i <= n; i++) //输出一种排列(1-n号箱子中的扑克牌编号)
{
cout << a[i];
}
cout << endl;
return; //返回之前的一步(最近一次调用dfs函数的地方)
}
//当站在第step个箱子面前应该放什么牌
//依次实验1、2、3、4.....是否可行
for (i = 1; i <= n; i++)
{
//判断扑克牌i是否还在手上
if (book[i] == 0)
{
a[step] = i; //将第i号扑克牌放到第step个箱子中
book[i] = 1; //将book[i]设置为1则表示第i张扑克牌不在手中
dfs(step + 1); //第step个箱子放好后,走到下一个箱子
book[i] = 0; //同时收回刚才尝试的扑克牌
}
}
return;
}
int main() {
n=3;
dfs(1);
return 0;
}