"Sword Finger Offer"-27. Arrangement of strings

1. Knowledge points of this question

String

2. Title description

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

3. Problem solving ideas

The full arrangement of the required string can be seen as two steps:

  1. Find all the characters that may appear in the first position, that is, swap the first character and the following characters in turn.
  2. Fix this character and find the arrangement of all the characters after it.

Obviously this is a typical recursive idea, and the recursive exit is when the last character is fixed.

Insert picture description here

4. Code

public class Solution {
    
    
    ArrayList<String> result = new ArrayList<>();

    /**
     * 返回字符串的全排序结果
     * @param str
     * @return
     */
    public ArrayList<String> permutation(String str) {
    
    
        // 字符串为空时
        if (str == null || str.length() == 0) {
    
    
            return result;
        }
        permutation(str.toCharArray(), 0);
        // 从小到大排序
        Collections.sort(result);
        return result;
    }

    public void permutation(char[] str, int begin) {
    
    
        // 对最后一个字符固定的时候,退出递归
        if (begin == str.length - 1) {
    
    
            // 去重
            String s = String.valueOf(str);
            if (!result.contains(s)) {
    
    
                result.add(s);
            }
        } else {
    
    
            for (int i = begin; i < str.length; i++) {
    
    
                // 求所有可能出现在第一个位置的字符
                swap(str, begin, i);
                // 求后面所有字符的排列
                permutation(str, begin + 1);
                // 还原
                swap(str, begin, i);
            }
        }
    }

    public void swap(char[] str, int i, int j) {
    
    
        char temp = str[i];
        str[i] = str[j];
        str[j] = temp;
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/112794752