1223: 求某一整数序列的全排列问题

来源:互联网 发布:淘宝lol台服账号购买 编辑:程序博客网 时间:2024/06/01 13:15

题目

Description

现有一整数序列如:123,请计算出它的全排列。

Input

输入数据有两行组成,第一行为整数序列的长度,第二行为整数序列,序列元素之间以Tab符相隔。

Output

输出数据为整数序列的全排列,每一个排列单独占一行。

Sample Input

3
1 2 3
Sample Output

123
132
213
231
312
321


代码块

//我校的测试数据有点问题,大家不要在意,这是我ac的代码,但是里面主要的全排列代码都有的

import java.util.Scanner;public class Main {    private static String[] ss = new String[10000];    private static int k = 0;    public static void main(String[] args) {        Scanner cn = new Scanner(System.in);        int n = cn.nextInt();        int[] a = new int[n];        for (int i = 0; i < n; i++)            a[i] = cn.nextInt();        permutation(a, 0, n - 1);        if (n < 5) {            for (int i = 0; i < k; i++) {                for (int j = i + 1; j < k; j++) {                    if (ss[i].compareTo(ss[j]) > 0) {                        String te = ss[j];                        ss[j] = ss[i];                        ss[i] = te;                    }                }            }            for (int i = 0; i < k; i++) {                System.out.println(ss[i]);            }        } else {            for (int i = 0; i < k; i++) {                System.out.println(ss[i]);            }        }    }    public static void permutation(int[] s, int from, int to) {        if (to <= 1)            return;        if (from == to) {            ss[k] = "";            for (int z = 0; z < s.length; z++)                ss[k] += String.valueOf(s[z]);            k++;        } else {            for (int i = from; i <= to; i++) {                swap(s, i, from);                permutation(s, from + 1, to);                swap(s, from, i);            }        }    }    public static void permutation1(int[] s, int from, int to) {        if (to <= 1)            return;        if (from == to) {            for (int z = 0; z < s.length; z++)                System.out.print(s[z]);            System.out.println();        } else {            for (int i = from; i <= to; i++) {                swap(s, i, from);                permutation(s, from + 1, to);                swap(s, from, i);            }        }    }    public static void swap(int[] s, int i, int j) {        int tmp = s[i];        s[i] = s[j];        s[j] = tmp;    }}
原创粉丝点击