Prove safety offer: string arrangement (dynamic programming, recursive)

topic:

A string input, prints out all permutations of the characters in the string in lexicographic order. For example input string abc, abc print all strings of characters a, b, c can be arranged out, acb, bac, bca, cab and cba.

Enter a description:

Enter a string of not more than 9 (possibly repeated characters), characters include only lowercase letters.

answer:

Recursive method, as follows:

import java.util.ArrayList;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        ArrayList<String> result = new ArrayList<>();
        if(str==null||str.length()==0){
            return result;
        }
        for(int i=0;i<str.length();i++){
            if(i>0&&str.charAt(i)==str.charAt(i-1)){
                continue;
            }
            StringBuilder substr = new StringBuilder().append(str.substring(0,i));
            if(i+1<str.length()){
                substr.append(str.substring(i+1,str.length()));
            }
            ArrayList<String> temp = Permutation(substr.toString());
            if(temp.size()>0){
                for(String ss:temp){
                    StringBuilder sb = new StringBuilder().append(str.charAt(i)).append(ss);
                    result.add(sb.toString());
                }
            }else{
                StringBuilder sb = new StringBuilder().append(str.charAt(i));
                result.add(sb.toString());
            }
            
        }
        return result;
    }
    
}

 

Published 92 original articles · won praise 2 · Views 8396

Guess you like

Origin blog.csdn.net/wyplj2015/article/details/104908325