Full Permutation and combination of common algorithms

Source: Internet
Author: User

Full Permutation and combination of common algorithms

The full sorting algorithm is a common algorithm, and its practices are also diverse.

First, let's take A look at the most intuitive thinking. The idea is as follows: if there are no repeated elements, input an array A and insert it into another array B, if B already contains this element, skip this step; otherwise, insert array B. Let's take a look at the specific code:

<span style="font-size:14px;">public static void permutation1(final String str, String buffer){        if (str.length() == buffer.length()){            System.out.println((num++) + ":" + buffer);            return;        }        for (int i = 0; i < str.length(); i++){            if (buffer.indexOf((int)str.charAt(i)) < 0){                permutation1(str, buffer + str.charAt(i));            }        }    }</span>

This code is easy to understand, so we will not talk about it. It has the disadvantage that it cannot be repeated. Then we change it and place a status bit for each value, if the inserted prefix is 1 and none is 0, we have the second method:

<span style="font-size:14px;">public static void permutation2(final char[][] array, String result, int len){        if (result.length() == len){            System.out.println(result);        }else{            for (int i = 0; i < len; i++){                if (array[i][1] == 0){                    array[i][1] = 1;                    permutation2(array, result + array[i][0], len);                    array[i][1] = 0;                }            }        }    }</span>
Of course, it also has disadvantages. We need to convert the input array before this. For example

<span style="font-size:14px;">public static void main(String[] args) {        String str = "abcd";        char[][] array = new char[str.length()][2];        for (int i = 0; i < str.length(); i++){            array[i][0] = str.charAt(i);            array[i][1] = 0;        }        String result = new String();        permutation2(array, result, str.length());    }</span>
There is another recursive method. If our array is abc, then abc, acb, bac, bca, CBA, and cab are all arranged.

That is to say, the sum starting with a is in the full arrangement of {B, c}, the sum starting with B is in the full arrangement of {a, c}, and the sum starting with c is in the full arrangement of {a, B.

P = {r1, r2, r3, r4...}, set pn = p-{rn}

Perm (p) = r1perm (p1) + r2perm (p2) + r3perm (p3) + ....

We can see that each full arrangement can be further divided into more full Sub-arrangement, and each sub-arrangement can be seen as the first letter and other letters to change the location. Therefore, we can use the following code to calculate the result:

<span style="font-size:14px;">public static void swap(char[] array, int from, int to){        char temp = array[from];        array[from] = array[to];        array[to] = temp;    }    public static void permutation3(char[] array, int n){        if (n == array.length){            System.out.println(new String(array));        }else {            for (int i = n; i < array.length; i++){                swap(array, i, n);                permutation3(array, n + 1);                swap(array, i, n);            }        }    }</span>

However, we have introduced all recursive algorithms. What should we do if we want non-recursive algorithms.

First, let's take a look at such a string 1234, and we need to arrange it in full. How can we find it? 1243,1342 and so on can we get it all. However, how can we push this string and so on. First, we stipulate that we need to sort the input strings, smaller than the first and later. Then we need to find the point whose number is earlier than the number after the previous thought. We need to ask him to replace the point, for example, 938740, from the back to the front, and 3 is a replacement point. After finding the replacement point, we continue to look for it from the back and find the first number greater than him. It is still in the above example: 937840, then the number is 4. Now, replace them. Now the number is 947830. Then we need to reverse it from the replacement point, convert 7840 to 0478, and merge 930478 with the previous number. Then, repeat this action to find all the numbers.


<span style="font-size:14px;">public static void reversal(char array[], int from, int to){        while (from < to){            swap(array, from++, to--);        }    }    public static boolean hasNext(char[] array){        if (array.length == 0 || array == null){            return false;        }        int endIndex = array.length - 1;        int q = endIndex - 1;        int p = endIndex;        while (q >= 0){            if (array[q] < array[q + 1]){                while (array[q] > array[p]){                    p--;                }                swap(array, p, q);                reversal(array, q + 1, array.length - 1);                return true;            }            q--;        }        reversal(array, 0, array.length - 1);        return false;    }    public static void main(String[] args) {        char[] array = "abc".toCharArray();        do {            System.out.println(array);        } while (hasNext(array));    }</span>

However, what should I do if there is a string with repeated characters. And if some characters are in a certain order, I said I was still thinking, if you know, welcome to know the message mail is OK: 630841816@qq.com




The above is a full arrangement. Next we will discuss the full combination.

Let's take a look at an example. The full combination of p = {a, B, c}: asse (p) ={}, {a}, {B}, {c }, {AB }.....

Here we can see some rules:

{}=> 000 {a }=> 001 {B }=> 010...

We can correspond them to each other. In this way, we have a value ranging from 0 ~ The value of size (asse (p) must represent a unique value.

So we can:

<Span style = "font-size: 14px;"> public static void assembly (char [] array) {int num; // The total number of groups num = 1 <array. length; for (int I = 0; I <num; I ++) {StringBuffer buffer = new StringBuffer (); for (int j = 0; j <array. length; j ++) {if (I & (1 <j)> 0) {buffer. append (array [j]) ;}} System. out. println (buffer) ;}}</span>


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.