[CC150] Get all permutations of a string

Problem: Compute all permutations of a string of unique characters.

此题用循环的方式不好做,下面是一种递归的思路:

把给的字符串看成一个字符集合,每次从这个集合里拿出一个字符来填到下面的空格中。填的顺序从左到右。

把a1填到第一个空格里是一种情况,集合剩下的部分填到2-9的空格里;

把a2填到第一个空格里是一种情况,集合剩下的部分填到2-9的空格里;

。。。。。。

这样递归的进行下去,直到集合里没有剩余,所有的情况就被穷尽了。

    public ArrayList<String> getPerms(String str){
        ArrayList<String> result = new ArrayList<String>();
        getPerms("", str, result);
        return result;
    }
    
    public void getPerms(String prefix, String str, ArrayList<String> result){
        if(str == null || str.length() == 0){
            result.add(prefix);
            return;
        }
        
        for(int i = 0; i < str.length(); ++i){
            char ch = str.charAt(i);
            getPerms(prefix+ch, str.substring(0, i) + str.substring(i+1), result);
        }
    }
原文地址:https://www.cnblogs.com/Antech/p/3771875.html