本文實例講述了Java實現字符數組全排列的方法。分享給大家供大家參考,具體如下:
import org.junit.Test;public class AllSort { public void permutation(char[] buf, int start, int end) { if (start == end) {// 當只要求對數組中一個字母進行全排列時,只要就按該數組輸出即可 for (int i = 0; i <= end; i++) { System.out.print(buf[i]); } System.out.println(); } else {// 多個字母全排列 for (int i = start; i <= end; i++) { char temp = buf[start];// 交換數組第一個元素與后續的元素 buf[start] = buf[i]; buf[i] = temp; permutation(buf, start + 1, end);// 后續元素遞歸全排列 temp = buf[start];// 將交換后的數組還原 buf[start] = buf[i]; buf[i] = temp; } } } @Test public void testPermutation() throws Exception { char[] buf = new char[] { 'a', 'b', 'c' }; permutation(buf, 0, 2); } }
運行測試,輸出結果:
abc
acb
bac
bca
cba
cab
希望本文所述對大家Java程序設計有所幫助。
新聞熱點
疑難解答