用Java编写程序;求字母A和B的各种排列组合(递归思想)

用此方法 public static void generate(int n, String s, ArrayList<String> results) 例如n =2 输出结果“AA”,“AB”, "BA", "BB" 。n =3时输出结果 “AAA”,“AAB”,“ABA”,“BAA”,“ABB”,“BBA”,“BAB”,“BBB". 最终结果保存在ArrayList<String> results里

万分感谢

//PS:不太明白函数中String s的意义,所以忽略了。
import java.util.ArrayList;  
import java.util.List;  
  
  
public class CompoundString {  
    
    private static void generate(int n,List<String> results) {   
        if(n==1){
         return;
        }
     List<String> resultsTemp_A = new ArrayList<String>();
     List<String> resultsTemp_B = new ArrayList<String>();
     for(String str : results){
         String temp_A = str+"A";
         resultsTemp_A.add(temp_A);
         String temp_B = str+"B";
         resultsTemp_B.add(temp_B);
        }
     //此处results引用不能改变,否则任何修改对main函数中的results都无效
     results.clear();
     results.addAll(resultsTemp_A);
     results.addAll(resultsTemp_B);
     generate(n-1, results);  // recursive
    }  
  
    public static void main(String[] args) {  
     List<String> results = new ArrayList<String>();
     results.add("A");
     results.add("B");
     generate(8, results);
     for(String str : results){
     System.out.println(str);
     }
    }  
}

温馨提示:答案为网友推荐,仅供参考
相似回答