天天看點

藍橋杯 字元串的全排列 JAVA

問題描述:

    一組字元串的全排列,按照全排列的順序輸出,

并且每行結尾無空格。

輸入:

    輸入一個字元串

輸入示例:

    請輸入全排列的字元串:

    abc

輸出示例:

    a b c

    a c b

    b a c

    b c a

    c b a

    c a b

import java.util.Scanner;

public class Main{
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		String s1 = scanner.nextLine();  // 輸入字元串
		char[] num = s1.toCharArray();   // 轉換字元數組
		Full_Permutation(num, 0);        // 調用方法
	}
	
	public static void Full_Permutation(char arr[], int n) {   // 确認某個排列的第k位
		if (n == arr.length) {                                 // 全部确認
			for (int i = 0; i < arr.length; i++) {
				System.out.print(arr[i] + " ");                // 輸出
			}
			System.out.println();                              // 換行
		}
		for (int i = n; i < arr.length; i++) {		           // 標明第k位
			char temp = arr[i];                                // 将第i位和第k位交換
			arr[i] = arr[n];
			arr[n] = temp;			
			Full_Permutation(arr, n + 1);                      // 移交下一層确認k+1位			
			temp = arr[i];                                     // 回溯
			arr[i] = arr[n];
			arr[n] = temp;
		}
	}
}
           

小劇場:是很美麗的花火。It’s a beautiful flower.