如何輸出字符串的所有組合


問題描述:假如字符串中所有字符都不重復,如何輸出字符串的所有組合。例如:abca,結果應是a,b,c,ab,ac,bc,abc。最容易想到的就是遞歸了,但效率會變得很差,因為棧被調用了2^n次方,為了提高效率,可以構造一個長度為n的01字符串,表示輸出結果中是否包含某個字符,例如:001->c,010->b,101->ac......,所以原題就是要求輸出"001"-"111"這2^n-1個組合對應的字符串。

public static void main(String[] args) {

  String s = "abc";
  ArrayList<String> result = combineString(s);
  for(String r : result){
    System.out.println(r);
  }
}

private static ArrayList<String> combineString(String s) {
  int len = s.length();
  ArrayList<String> list = new ArrayList<String>();
  int count = (int) (Math.pow(2, len));
  for(int i = 1; i < count; ++i){
    String temp = "";
    String str = Integer.toBinaryString(i);
    while(str.length() < len){
      str = "0" + str;
    }
    for(int j = 0; j < str.length(); ++j){
      if(str.charAt(j) == '1'){
        temp += s.charAt(j);
      }
    }
    list.add(temp);
  }
  return list;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM