18.4: Printing all permutations of a string

print all permutations of a string

Method 1: Violent method.

insert image description here

	//方法一:暴力方法。
    public static List<String> permutation1(String s) {
    
    
        //str是一个存储字符类型的有序表。
        ArrayList<Character> str = new ArrayList<>();
        //将字符串中的类型存储在str中。
        for (Character c : s.toCharArray()) {
    
    
            str.add(c);
        }
        String path = "";
        List<String> ans = new LinkedList<>();
        process(str, path, ans);
        return ans;
    }

    //str:字符数组。
    //path:记录之前选择的答案。
    //ans:记录最终的结果。
    public static void process(ArrayList<Character> str, String path, List<String> ans) {
    
    
        if (str.isEmpty()) {
    
    
            ans.add(path);
            return;
        }


        for (int i = 0; i < str.size(); i++) {
    
    
            char value = str.get(i);
            str.remove(i);
            process(str, path + String.valueOf(value), ans);
            //还原现场,之前在那就放在哪。
            str.add(i, value);
        }
    }

Pay attention to restore the site, put it back to the position where it was before, to ensure the cleanliness of the original data.

Because if the data is confused, the results will be inaccurate.

for example:

"abcd" selects a as the beginning at the beginning, and the rest of bcd enters recursion, and finally completes the data recording beginning with a. Come out of the recursion, then str.add(value);

Directly insert a at the end, assuming that the current str = bcda, then i++; i == 1, the next data taken from str is c, not the b I want, and our results are all messed up.

It can be seen from this that after the recursion is completed, the number in the previous position will be put back in that position. This ensures data integrity.

Method 2: The method of exchanging.

	//方法二:
    public static List<String> permutation2(String s) {
    
    
        char[] str = s.toCharArray();
        List<String> ans = new LinkedList<>();
        process(str, 0, ans);
        return ans;
    }

	//index:表示的是当前的位置。
    public static void process(char[] str, int index, List<String> ans) {
    
    
        if (index == str.length) {
    
    
            ans.add(String.valueOf(str));
            return;
        }

        for (int i = index; i < str.length; i++) {
    
    
            swap(str, index, i);
            process(str, index + 1, ans);
            //还原现场,之前在那就放在哪。
            swap(str, index, i);
        }
    }

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

Note that you still need to restore the scene here, and put back where it was before.

for example:

insert image description here

When 0 is exchanged with 2, a goes to the head again, and what I want is c to be on the head. The reason for this situation is that the data is all messed up, and exchanging on the messy data will cause some results to be unavailable.

If you want to get the correct result, you must perform transformation on clean data (original data), so after each step is completed, restore the scene to ensure that the data is consistent with the original data.

Print all permutations of a string, requiring no repeated permutations

Pruning strategy:

	//打印一个字符串的全部排列,要求不要出现重复的排列
    public static List<String> permutation3(String s) {
    
    
        char[] str = s.toCharArray();
        List<String> ans = new LinkedList<>();

        process2(str, 0, ans);
        return ans;
    }

    public static void process2(char[] str, int index, List<String> ans) {
    
    
        if (index == str.length) {
    
    
            ans.add(String.valueOf(str));
            return;
        }

        boolean[] visited = new boolean[256];// ------------------------------------注意
        for (int i = index; i < str.length; i++) {
    
    
            //str[i] -> 找到该字符的ASCII码,visited[str[i]] -> 判断该字符之前是否存在过。
            if (!visited[str[i]]) {
    
    
                visited[str[i]] = true;
                swap(str, index, i);
                process2(str, index + 1, ans);
                //还原现场,之前在那就放在哪。
                swap(str, index, i);
            }
        }
    }

boolean[] visited = new boolean[256]; The position of this array is crucial.

Each layer creates a visited array to determine whether a character has appeared in this layer. A visited array is not created globally. If so, an error will result.

Supongo que te gusta

Origin blog.csdn.net/SCR1209/article/details/131112340
Recomendado
Clasificación