某厂实习生笔试题-数组全排列

题目描述

输入一个数组,以空格隔开,要求按一下顺序输出其全排列。

样例:

输入:

1 2 3

输出:

123 132 213 231 312 321

备注:输入和输出都是自然数数组。

程序设计

毫无疑问,这道题我首先想到的是运用递归来解决。

对于输入的一个数组n,其排列方式可看作是在n个位置,从第一个位置开始,到最后一个位置,放置所输入的n个数。

假设我们先将输入的n个数放在一个箱子里。

对第 step (0 ≤ step <n)个位置,我们可以选择除了前面 step 个数以外的 step - i 个数中的一个(即箱子里剩下的下一个(按输入顺序))来放置。

当 step = n 时,说明n个位置均已放置好对应的数,作为一种排列方式输出。

这时,再返回上一层递归,返回之后要将刚刚放置在n - 1这个位置的数,放回箱子里。

即step = n - 1时,即最后一个位置,箱子里只有一个数可以放,同理再返回上一层递归。

返回之后要将刚刚放置在n - 2的位置的数放回箱子里。

即step = n - 2时,即倒数第二个位置,箱子里只有两个数可以放…

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static int n = 0;
    public static int[] array;
    public static int[] array2;//装数字的箱子
    public static boolean[] array3;//记录箱子中对应的数字是否已经被取出

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num;
        ArrayList<Integer> arrayList = new ArrayList<>();
        while(scanner.hasNext()){
            num = scanner.nextInt();
            arrayList.add(num);
            n++;
        }
        int i=0;
        array = new int[n];
        array2 = new int[n];
        array3 = new boolean[n];
        for ( Integer each:arrayList) {
            array[i++] = each;
        }
        for (int j = 0; j < n; j++) {
            array3[j] = true;
        }
        fullPermutation(0);
    }
    public static void fullPermutation(int step){
        if (step == n)
        {
            for (int j = 0; j < n; j++) {
                System.out.print(array2[j]);
            }
            System.out.print(" ");
            return;
        }
        for (int i = 0; i < n; i++) {
            if (array3[i]){
                array2[step] = array[i];
                array3[i] = false;//该数已从箱子里取出
                fullPermutation(step + 1);
                array3[i] = true;//放回该数至箱子
            }
        }
        return;
    }
}

递归的思路,我用语言描述起来比较绕,大家可以将提供的样例,代入到程序跑一遍,便会有更清晰的认识。

原创文章 5 获赞 2 访问量 512

猜你喜欢

转载自blog.csdn.net/weixin_43191072/article/details/104959688