字符串或数字串全排列问题

来源:互联网 发布:阿里云os5.1系统root 编辑:程序博客网 时间:2024/04/30 22:42

字符串或数字串全排列问题

最近面试到一些全排列问题;如123 输出123 213 231 132 312 321;

用java语言实现:

import java.util.LinkedList;
import java.util.Scanner;

public class A {

static int number = 0;static LinkedList<Integer> list = new LinkedList<>();public static void main(String[] args) {    System.out.println("please write yuur want number .");;    Scanner scanner = new Scanner(System.in);    int[] i = new int[scanner.nextInt()];    System.out.println("please write yuur want ");;    for (int j = 0; j < i.length; j++) {        i[j] =scanner.nextInt();    }    fuc(i);}private static void fuc(int[] inin) {    if (inin == null)        return;    if (inin.length == 1) {        list.add(inin[0]);        System.out.println(list+ "  "+number++);        list.removeLast();        return;    }    for (int i = 0; i < inin.length; i++) {        inin = swapXY(inin, 0, i);        list.add(inin[0]);        fuc(remove(inin));        list.removeLast();    }}private static int[] swapXY(int[] i, int x, int y) {    int m;    if ((x < 0 || x > i.length - 2) && (y < 0 || y > i.length - 2))        return i;    m = i[x];    i[x] = i[y];    i[y] = m;    return i;}private static int[] remove(int[] i) {    int[] target = new int[i.length - 1];    for (int j = 0; j < i.length - 1; j++) {        target[j] = i[j + 1];    }    return target;}

}
终端:
please write yuur want number .
4
please write yuur want
1 2 3 4
[1, 2, 3, 4] 0
[1, 2, 4, 3] 1
[1, 3, 2, 4] 2
[1, 3, 4, 2] 3
[1, 4, 2, 3] 4
[1, 4, 3, 2] 5
[2, 1, 3, 4] 6
[2, 1, 4, 3] 7
[2, 3, 1, 4] 8
[2, 3, 4, 1] 9
[2, 4, 1, 3] 10
[2, 4, 3, 1] 11
[3, 1, 2, 4] 12
[3, 1, 4, 2] 13
[3, 2, 1, 4] 14
[3, 2, 4, 1] 15
[3, 4, 1, 2] 16
[3, 4, 2, 1] 17
[4, 1, 2, 3] 18
[4, 1, 3, 2] 19
[4, 2, 1, 3] 20
[4, 2, 3, 1] 21
[4, 3, 1, 2] 22
[4, 3, 2, 1] 23

0 0