Permutation Generation

Description
Enumerate all the permutations with size n and output them. You should output these permutations in lexicographical order.

Input
An integer n (n<=9).

Output
Output all the permutations with size n.

Sample Input
3

Sample Output

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

Hint
题目可以用printf输出,并且注意行末不输出空格
WJT的答案

#include <iostream>
using namespace std;

int n;
bool b[20];
int a[20];
void work(int x)
{
    if(x==n+1)
    {
        for(int i=1;i<=n;i++)
        cout<<a[i]<<" ";
        cout<<endl;
        return;
    }
    for(int i=1;i<=n;i++)
    if(!b[i])
    {
        b[i]=1;
        a[x]=i;
        work(x+1);
        b[i]=0;
    }
}
int main(){
    cin>>n;
    work(1);
}

Yizuodi的答案(和WJT的答案类似)

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

int n;
int s[10], f[10], result[10];

void pers(int i)
{
    if (i == n)
    {
        for (int j = 0; j < n; j++)
        {
            cout << result[j] << " ";
        }
        cout << endl;
    }
    else
    {
        for (int j = 0; j < n; j++)
        {
            if (f[j] == 0)
            {
                result[i] = s[j];
                f[j] = 1;
                pers(i + 1);
                f[j] = 0;
            }
        }
    }
}
int main()
{
    cin >> n;
    for (int i = 0; i < n; i++) //用于存储写入的数字
    {
        s[i] = i + 1;
    }
    for (int i = 0; i < n; i++)
    {
        f[i] = 0;
    }
    pers(0);
}
上一篇: heap 下一篇: Subset Generation I
支持 makedown语法