ACM-挑战题之排列生成

题目描述:挑战题之排列生成

一自然数N,设N为3,则关于N的字典序排列为123,132,213,231,312,321。对于一个自然数N(1<= N <= 9 ) , 你要做的便是生成它的字典序排列。

输入

第一行为自然数N。

输出

输出对应于N的字典序排列,每个排列占一行。

样例输入

3

样例输出

123
132
213
231
312
321

思路:两种解法:1.按照位置放数字 2.按照数字放位置。
备注:使用数字和保存结果,直接输出每次结果即可,不然的话需要输出数组,增加时间消耗。。

// 挑战题之排列生成.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"


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

const int MAX = 100;
int n, vis[MAX];

void DFS(int pos,int ans)
{
    if (pos == n) { printf("%d
", ans); return; }

    for (int i = 1; i <= n; i++)
    {
        if (!vis[i])
        {
            vis[i] = 1;            
            DFS(pos + 1, 10 * ans + i);
            vis[i] = 0;
        }
    }
}

int main()
{
    while (cin >> n)
        DFS(0, 0);


    return 0;
}
原文地址:https://www.cnblogs.com/x739400043/p/8538708.html