本帖最后由 e10my 于 2014-5-24 17:50 编辑
- /**
- * @author e10my
- * 显示出一个字符串的所有排列组合.
- * 例:
- * 原始字符串是"abc",打印得到下列所有组合情况:
- * "a" "b" "c"
- * "ab" "bc" "ca" "ba" "cb" "ac"
- * "abc" "acb" "bac" "bca" "cab" "cba"
- */
- public class PaiLie {
-
- public void runPermutation(char[] a, int n) {
-
- if(null == a || a.length == 0 || n <= 0 || n > a.length)
- return;
-
- char[] b = new char[n];//辅助空间,保存待输出组合数
- getCombination(a, n , 0, b, 0);
- }
- public void getCombination(char[] a, int n, int begin, char[] b, int index) {
-
- if(n == 0){//如果够n个数了,输出b数组
-
- getAllPermutation(b,0);//得到b的全排列
- return;
- }
-
- for(int i = begin; i < a.length; i++){
-
- b[index] = a[i];
- getCombination(a, n-1, i+1, b, index+1);
- }
-
- }
- public void getAllPermutation(char[] a,int index){
- /*与a的元素个数相同则输出*/
- if(index == a.length-1){
- System.out.print("\'");
- for(int i = 0; i < a.length; i++){
- System.out.print(a[i]);
- }
- System.out.print("\' ");
- return;
- }
-
- for(int i = index; i < a.length; i++){
-
- swap(a ,index, i);
- getAllPermutation(a, index+1);
- swap(a ,index, i);
- }
- }
- public void swap(char[] a, int i, int j) {
-
- char temp = a[i];
- a[i] = a[j];
- a[j] = temp;
- }
- public static void main(String[] args){
-
- PaiLie robot = new PaiLie();
- String str = "abc";
- char[] a = str.toCharArray();
- //int[] a = {1,2,3};
- //int n = 2;
- for(int i = 0; i<=str.length();i++){
- robot.runPermutation(a,i);
- System.out.println( );
- }
- }
- }
复制代码
这道题很有意思, 想了好长时间也没有想到思路.最终还是引用了@nash_的一个算法
via : http://blog.csdn.net/zmazon/article/details/8351611
以上代码经过源代码改善得到.请慎重参考.
如果可以找到更好的方法, 希望共同探讨.
|