AcWing 94. 遞歸實現排列型枚舉

AcWing 94. 遞歸實現排列型枚舉

題目連接ios

把 1~n 這 n 個整數排成一行後隨機打亂順序,輸出全部可能的次序。c++

輸入格式

一個整數n。spa

輸出格式

按照從小到大的順序輸出全部方案,每行1個。code

首先,同一行相鄰兩個數用一個空格隔開。blog

其次,對於兩個不一樣的行,對應下標的數一一比較,字典序較小的排在前面。遞歸

數據範圍

1≤n≤9圖片

輸入樣例:

3

輸出樣例:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

題解

從小到大的順序枚舉,就會獲得字典序最小的序列
若是變量爲全局變量,那麼變量初值默認爲0;
若是變量爲局部變量,那麼變量初值爲隨機值。
ci

代碼實現

#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>

using namespace std;
const int N=10;//數據範圍爲1<=n<=9,咱們是從i=1開始的,所以N取10; 
int n;
int num[N];//0表示沒有被遍歷到,1~n表示放置了哪些數 
bool st[N];//true  or  false(表示是否用過) 
void dfs(int u)
{
	if(u>n)//表示已經枚舉完畢 
	{
		for(int i=1;i<=n;i++)	cout<<num[i];
		cout<<endl;
		return;
	}
	for(int i=1;i<=n;i++)
	if (!st[i])//若是第i個數沒有被用過 
	{
		num[u]=i;
		st[i]=true;
		dfs(u+1);
		
		num[u]=0;//又回到最初的狀態,結合我發的題解圖片去理解 
		st[i]=false;
	} 
}
int main()
{
	cin>>n;
	dfs(1);
	return 0;
}
相關文章
相關標籤/搜索