请问下:给定一个字符串,如何等到该字符串的所有组合的可能???比如:字符串"ab",要得到"ab","ba"。我现在没有分,给不了大家,希望大家帮帮忙!非常谢谢!

解决方案 »

  1.   

    这个问题 理解为  全排列的问题:
    public class QuanPaiLei { public static int MAX = 4; public static boolean state[] = new boolean[MAX + 1]; public static int item[] = new int[MAX + 1]; public static String element[] = { "a", "b", "c","d" }; public static void main(String[] args) {
    DoPermutation(1);
    } public static void DoPermutation(int pos) {
    if (pos > MAX) {
    for (int j = 1; j <= MAX; j++)
    System.out.print(element[item[j] - 1]);
    System.out.println();
    return;
    }
    for (int i = 1; i <= MAX; i++) {
    if (!state[i]) {
    state[i] = true;
    item[pos] = i;
    DoPermutation(pos + 1);
    state[i] = false;
    }
    }
    }
    }
    先把字符串,转成一个字符数组
    接下来就是 全排列的问题
    说实在我对这程序,也是理解 有点问题, 但是它实现了这个功能
      

  2.   

    谢谢各位!今天找了一下,发现有一种办法是用递归的.
    import java.util.*;
    public class Main{
    public static void test(String number ,String result ,int len){
          //number是这个数, result表示结果   开始时传入 空字符 ,  len是这个数的长度
          if(result.length()==len){
           System.out.println(result);
          }
          else{
           for(int i=0;i<number.length();i++){
            if(result.indexOf(number.charAt(i))<0){
             test(number, result+number.charAt(i), len);
            }
           } 
          }
         }
    public static void main(String args[]) throws Exception { 
       String str="ac";
       int length=str.length();
       String res="";
       test(str,res,length);
     

    }