Codeup——608 | 问题 A: 【递归入门】全排列

题目描述

排列与组合是常用的数学方法。
先给一个正整数 ( 1 < = n < = 10 )
例如n=3,所有组合,并且按字典序输出:
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

输入

输入一个整数n( 1<=n<=10)

输出

输出所有全排列

每个全排列一行,相邻两个数用空格隔开(最后一个数后面没有空格)

样例输入

3

样例输出

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

方法一:DFS递归写法

#include <iostream>
#include <cstdio>
using namespace std;
int n;
int a[11];
bool hashtable[11]={
    
    0};

void dfs(int step){
    
    
	if(step==n+1){
    
    
		printf("%d",a[1]);
		for(int i=2;i<=n;i++)
			printf(" %d",a[i]);
		printf("\n");
		return;
	}
	for(int i=1;i<=n;i++){
    
    
		if(!hashtable[i]){
    
    
			hashtable[i]=true;
			a[step]=i;
			dfs(step+1);
			hashtable[i]=false; 
		}
	}
}

int main()
{
    
    
	scanf("%d",&n);
	dfs(1);
	return 0;
} 

方法二:STL中next_permutation() 函数写法

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;

int main()
{
    
    
	int n,i;
	int a[10]={
    
    1,2,3,4,5,6,7,8,9,10};
	scanf("%d",&n);
	do{
    
    
		printf("%d",a[0]);
		for(i=1;i<n;i++)
			printf(" %d",a[i]);
		printf("\n");
	}while(next_permutation(a,a+n));
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_44888152/article/details/107047606