字符串全排列

来源:互联网 发布:手机解压缩软件 编辑:程序博客网 时间:2024/06/02 03:24
[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import org.junit.Test;  
  2.   
  3. public class AllSort {  
  4.   
  5.     public void permutation(char[] buf, int start, int end) {  
  6.         if (start == end) {// 当只要求对数组中一个字母进行全排列时,只要就按该数组输出即可  
  7.             for (int i = 0; i <= end; i++) {  
  8.                 System.out.print(buf[i]);  
  9.             }  
  10.             System.out.println();  
  11.         } else {// 多个字母全排列  
  12.             for (int i = start; i <= end; i++) {  
  13.                 char temp = buf[start];// 交换数组第一个元素与后续的元素  
  14.                 buf[start] = buf[i];  
  15.                 buf[i] = temp;  
  16.   
  17.                 permutation(buf, start + 1, end);// 后续元素递归全排列  
  18.   
  19.                 temp = buf[start];// 将交换后的数组还原  
  20.                 buf[start] = buf[i];  
  21.                 buf[i] = temp;  
  22.             }  
  23.         }  
  24.     }  
  25.   
  26.     @Test  
  27.     public void testPermutation() throws Exception {  
  28.         char[] buf = new char[] { 'a''b''c' };  
  29.         permutation(buf, 02);  
  30.     }  
  31. }  

运行测试,输出结果:

abc
acb
bac
bca
cba
cab

0 0