Generate list of all possible permutations of a string

后端 未结 30 2841
故里飘歌
故里飘歌 2020-11-22 15:10

How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.

Any l

30条回答
  •  轮回少年
    2020-11-22 15:39

    permute (ABC) -> A.perm(BC) -> A.perm[B.perm(C)] -> A.perm[(*BC), (CB*)] -> [(*ABC), (BAC), (BCA*), (*ACB), (CAB), (CBA*)] To remove duplicates when inserting each alphabet check to see if previous string ends with the same alphabet (why? -exercise)

    public static void main(String[] args) {
    
        for (String str : permStr("ABBB")){
            System.out.println(str);
        }
    }
    
    static Vector permStr(String str){
    
        if (str.length() == 1){
            Vector ret = new Vector();
            ret.add(str);
            return ret;
        }
    
        char start = str.charAt(0);
        Vector endStrs = permStr(str.substring(1));
        Vector newEndStrs = new Vector();
        for (String endStr : endStrs){
            for (int j = 0; j <= endStr.length(); j++){
                if (endStr.substring(0, j).endsWith(String.valueOf(start)))
                    break;
                newEndStrs.add(endStr.substring(0, j) + String.valueOf(start) + endStr.substring(j));
            }
        }
        return newEndStrs;
    }
    

    Prints all permutations sans duplicates

提交回复
热议问题