字符串、數組的全排列問題

現實生活中有很多時候要用到計算幾個數或者幾種物品的全排列的問題,本文利用遞歸方法,用JAVA實現全排列的功能。

import java.util.Arrays;
import java.util.Scanner;

public class Permutation {

	/**
	 * @字符串全排列問題,即接收一組字符串,然後把每個字符的所有排列形式打印出來,並打印排列組數。
	 */
	static String input;
	static char[] aa;
	static int count = 0;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner console = new Scanner(System.in);
		System.out.println("請輸入一串字符串:");
		while (console.hasNext()) {
			input = console.nextLine();
			aa = input.toCharArray(); //把輸入的字符串放入一個char型數組中
			int length = aa.length-1;
			test(aa,0,length);
			System.out.println("共有"+count+"種排列方式");
		}
	}

	private static void test(char[] in,int start,int end) {
		// 採用遞歸的方式思考問題,把一串字符串分成兩部分:第一個字符和後面的字符串
		// start是指向第一個字符的遊標
		// end是字符數組最後一個字符的位置
		if(start==end){
			count++;
			System.out.println(Arrays.toString(in));
		}
		else{
			for(int i=start;i<=end;i++){
				char temp = in[start];
				in[start] = in[i];
				in[i] = temp;
			
			    test(in,start+1,end);
			    
				temp = in[start];
				in[start] = in[i];
				in[i] = temp;
			}
		}
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章