本文實(shí)例講述了Java實(shí)現(xiàn)字符數(shù)組全排列的方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
import org.junit.Test; public class AllSort { public void permutation( char [] buf, int start, int end) { if (start == end) { // 當(dāng)只要求對(duì)數(shù)組中一個(gè)字母進(jìn)行全排列時(shí),只要就按該數(shù)組輸出即可 for ( int i = 0 ; i <= end; i++) { System.out.print(buf[i]); } System.out.println(); } else { // 多個(gè)字母全排列 for ( int i = start; i <= end; i++) { char temp = buf[start]; // 交換數(shù)組第一個(gè)元素與后續(xù)的元素 buf[start] = buf[i]; buf[i] = temp; permutation(buf, start + 1 , end); // 后續(xù)元素遞歸全排列 temp = buf[start]; // 將交換后的數(shù)組還原 buf[start] = buf[i]; buf[i] = temp; } } } @Test public void testPermutation() throws Exception { char [] buf = new char [] { 'a' , 'b' , 'c' }; permutation(buf, 0 , 2 ); } } |
運(yùn)行測(cè)試,輸出結(jié)果:
abc
acb
bac
bca
cba
cab
希望本文所述對(duì)大家Java程序設(shè)計(jì)有所幫助。