全排列,STL版,dfs版

獲取全排列,可以深搜dfs,也可以STL的next_permutatiion,和prev_permutation,頭文件algorithm

STL真的方便,不過得注意奇奇怪怪的東西

next_permutatiion,和prev_permutation返回值true或者false,

當這個數組按照字典序有下一個(上一個)全排列的時候,返回true併產生這個全排列

沒有就返回false

#include <iostream>
#include <algorithm>
#include<cstdlib>
using namespace std;
int main() {
    int nums[3] = {3, 1, 2};//數組是無序的
    for(int i=0;i<6;i++)
    //循環全排列的個數次,就能產生所有的排列,但是沒有順序
    {
        next_permutation( nums, nums+3);//全排列,參數是首尾地址
        for( int i = 0; i < 3; i++ ) {
            cout << nums[i]<<" ";
        }
        cout << endl;
    }
    return 0;
}

dfs

#pragma warning(disable:4996)
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
int ans[100005],n;
bool vis[100005];
void dfs(int cnt)
{
	int i;
	if (cnt == n)
	{
		for (i = 0; i < n; i++)
		{
			printf("%d ", ans[i]);
		}
		printf("\n");
		return;
	}
	for (i = 1; i <= n; i++)
	{
		if (!vis[i])
		{
			vis[i] = 1;
			ans[cnt] = i;
			dfs(cnt + 1);
			vis[i] = 0;
		}
	}
}
int main()
{
	while (scanf("%d", &n) == 1)
	{
		dfs(0);
	}
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章