Array of all permutations

Source: Internet
Author: User

1. Issue background

Everyone who has studied mathematics knows what the whole arrangement means. Now how to use the computer programming language to implement the full array of arrays?

The full array of arrays can be used to solve the eight queens problem, see also: The full permutation solves the eight queen problem. At the same time, the full arrangement often appears in a written or interview, such as the full array of strings. The reason that it as a test, because it is moderately difficult, can not only investigate the recursive implementation, but also to further investigate the implementation of non-recursive, easy to distinguish the level of candidates. So it's important to master it.

2. Fully arranged recursive implementation of 2.1 solution ideas

The full arrangement means that all the elements in the collection are arranged in a certain order, using p (n, N) = n! to indicate the number of n elements that are all arranged. The first n in P (n, N) represents the number of elements, and the second n indicates how many elements to arrange.

Given an array of n elements, the fully arranged process can be described as follows:
(1) Arbitrarily take an element in the first position, there are n options;
(2) Then the remaining n-1 elements of another element in the second position of the n-1 choice, at this time can be regarded as the n-1 elements of the whole arrangement;
(3) Repeat the second step until the last element is fully arranged, that is, the last element is placed in the last position, and the entire arrangement ends.

As an example of an array of {* * +}, the whole sequence is as follows:
(1) 1 followed by (2,3) the full arrangement;
(2) 2 followed by (1,3) the full arrangement;
(3) 3 followed by the full arrangement.

This is illustrated below:

2.2 Advantages and disadvantages of recursive implementations

Due to the recursive decomposition of the problem, it is relatively easy to understand, but need to consume a lot of stack space, if the function stack space is not enough, then can not go on, and the function call overhead is also relatively large.

2.3 Concrete Implementations
#include <iostream>using namespace STD;intsum=0;//Total number of permutations//print array contentsvoidPrintint Array[],intLen) {printf("{"); for(intI=0; I<len;++i)cout<<Array[i]<<" ";printf("}\n");}//Implement two-digit switchingvoidSwapint* O,intIintj) {intTMP = O[i];    O[i] = O[j]; O[J] = tmp;}//Recursive implementation array is fully arranged and printedvoidPermutation (int Array[],intLenintIndex) {if(Index==len) {//full arrangement end++sum; PrintArray, Len); }Else         for(intI=index;i<len;++i) {//Swap the element I to the current index subscriptSwapArray, index,i);//Recursively arrange the remaining elements in a recursive mannerPermutation (Array, len,index+1);//Exchange The first element backSwapArray, index,i); }}intMain () {int Array[3]={1,2,3}; Permutation (Array,3,0);cout<<"sum:"<<sum<<endl; GetChar ();}

Note: when the loop swaps all the elements in an array with the first element, and then the subarray is fully arranged, the first element needs to be swapped back for the next element to be exchanged with the first element.

The results of the operation are as follows:

2.4 Consider repeating elements in an array element

In the case of the array {1,2,2}, if there is a duplicate element in the array, it becomes {}, then its entire arrangement cannot be solved completely according to the above method and needs to be changed slightly.

Because the full arrangement is to change the different elements to the current position, then the subsequent elements are perfection arranged. If you change the repeating element to the current position multiple times, the same arrangement appears. To avoid this, we prohibit changing the same element multiple times to the current position.

For example, for {1,2,2}, the first number 1 and the second Number 2 interchange get 212, then consider the first number 1 and the third Number 2 interchange, at this time because the third number equals the second number, so the first number is no longer exchanged with the third number. Considering again 212, its second number with a third number exchange can be solved 221. This completes the full-array generation.

In this way, we also get the rule of removing duplicates in the whole arrangement-- the whole permutation of the weight is the number of each number from the first number to the non-recurring digital exchange after it.

The modified code is as follows:

//whether ExchangeBOOL Isswap (intArray[],intLenint Index){ for(intI=Index+1; i<len;++i)if(array[Index]==array[i])return false;return true;}//recursive implementation of array with repeating elements all arrangedvoidPermutation (intArray[],intLenint Index){if(Index==len) {//full arrangement end++sum;    Print (Array,len); }Else         for(intI=Index; i<len;++i) {if(Isswap (Array,len,i)) {//new judgment whether to exchange                //Swap the element I to the current index subscriptSwap (Array,Index, i);//Recursively arrange the remaining elements in a recursive mannerPermutation (Array,len,Index+1);//Exchange The first element backSwap (Array,Index, i); }        }}

Experimental results:

3. Full-array non-recursive implementation of a 3.1-Permutation dictionary introduction

The full permutation of non-recursive implementations requires the use of a dictionary sequence after the arrangement of elements. The so-called dictionary order is ordered by the size of the elements to form an arrangement. For example {1,3,2} and {* *}, since the second element 2 of the previous arrangement is less than the second element 3 of the last arrangement, so the previous arrangement is in front, and the next one is in the back row.

3.2 Dictionary order generation full array of ideas

The idea of using dictionary sequences to generate a fully arranged algorithm is to set the arrangement of the elements in set a and to establish a relationship of one by one mappings in a certain order, in which all the permutations of the set are output. This order needs to be guaranteed, both to output the entire arrangement, and not to repeat the output of some sort of arrangement. The dictionary order is a way of outputting the whole arrangement with this kind of thought.

3.3 The basic process of creating a full array of dictionary sequences

Given an array of a[n], the basic process of using a dictionary-ordered output is described as follows:
(1) An ascending order of the size of an element to form a minimum order of the dictionary order;
(2) from the left A[0] start looking for the last element A[k], to meet A[k]<A[k+1](k<N?1)

Array of all permutations

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.