A series of collations on permutation problems

Source: Internet
Author: User

Recently, when I was doing leetcode, I did some arranging problems, such as next permutation (the next full permutation of the known current arrangement), permutations (given an integral set, perfection arrangement), permutations II (similar to permutations, only increases the occurrence of repeated elements), permutation Sequence (given the number 1...N, the n number of the full array of k). A little bit of finishing the next method, explained below:

First of all, of course, the problem of permutation is the classical problem in the algorithm, usually given n elements, which requires the entire arrangement of n elements, we generally adopt a recursive method, the introduction of the concept of set R (i), R (i) represents the original set of R after the set of the first. The full array of x, which we remember as perm (x). (r) Perm (x) indicates the arrangement preceded by the prefix R for each permutation of the perm (x) in full arrangement. As a result, we can easily get an inductive definition of perm (R):

Perm (R) = (r), when N=1, where r is the only element in R. When N>1, Perm (R) is composed of (R1) Perm (R1), (R2) Perm (R2),..... (RN) perm (RN) composition, R1,r2....rn constitute set R.

This recursive algorithm can be easily written by the above definition, which is a way to solve the problem of permutations. Of course there are other ways, before we introduce, let's talk about next permutation. This question is still more interesting, it has given a permutation, asking to find the next one, such as the next arrangement of its 1,3,2. By writing one or two full permutations it is not difficult to observe that the next permutation of the current arrangement is the next number larger than the current arrangement, of course, this number is required, that is, each bit can only use the number in the collection, and each number can only be used once. This is very understood, such as 21354, which can be seen as a permutation of the set {1,2,3,4,5}, and its next permutation should be the first number 21435 larger than 21354. But how do we find this number? We can see that in 21354 this arrangement, obviously 54, is already the largest number prefixed with 213, so 213 is the prefix, it is not possible to have a larger arrangement, so next consider the arrangement of 21 prefixes, when the problem is reduced to find the next permutation 354, Since 213 is not the prefix arrangement, it would naturally be expected to find the next 3-large number, followed by a prefix of 21, resulting in the smallest arrangement of the preceding prefix. We go from the right to the left, find the first number larger than 3, at this time 4, swap 3 and 4 position, the prefix is 214, leaving two number 5, 3. The smallest arrangement prefixed with 214 is 21435. So how do you do it in the program? You only need to compare the next two digits from right to left in order to find a smaller number than the previous number. At this point, the position and value of the previous number is recorded, and then the first number that is larger than this number is searched, the position is exchanged, the new prefix is generated, and then the remaining number, using the sort function, produces the smallest suffix, at which point the permutation is the desired one.

 Public voidNextpermutation (int[] nums) {     intLoc=nums.length-1; intLoc1=0;  for(inti=loc-1;i>=0;i--){         if(Nums[i]<nums[i+1]) {loc=i; Break;} }      if(loc!=nums.length-1){          for(inti=nums.length-1;i>loc;i--){              if(Nums[i]>nums[loc]) {loc1=i; Break;} }        intA=Nums[loc1]; Nums[loc1]=Nums[loc]; Nums[loc]=A; if(loc!=nums.length-2){            int[] inter=New int[Nums.length-loc-1];  for(inti=loc+1;i<nums.length;i++) inter[nums.length-i-1]=Nums[i];            Arrays.sort (inter);  for(inti=loc+1;i<nums.length;i++) nums[i]=inter[i-loc-1]; }     }    ElseArrays.sort (nums); //return nums;}

Introduce the next Permutatio method, we can easily use this method on the topic of permutations, first of all the elements in our team collection to sort the first arrangement, and then call next permutatio, constantly produce a new arrangement, Leetcode on this method is feasible.

Public list<list<integer>> permute (int[] nums) {     list<list<integer>> out=new ArrayList <List<Integer>> ();       if (nums.length==0) return out;     Arrays.sort (nums);     Boolean c=true;     while (c) {list<integer>inter=new arraylist<integer> (); for (int i=0;i<nums.length;i++) {   Inter.add (Nums[i]);} Out.add (inter); int count=0;for (int i=0;i<nums.length-1;i++) {   if (nums[i]<nums[i+1]) count++;} if (count==0) c=false;nums=nextpermutation (nums);//is the function of the last code      }      return out;}

This method of permutations II is the same way of thinking, after all, more repeating elements, just a bottle.

will go to permutation sequence this problem, at the outset I also intend to adopt this method (because of addiction, more because of lazy, do not think, want to save time), seemingly very simple, the result unexpectedly expired:

 PublicString Getpermutation (intNintk) {String out=NewString (); if(n==0)returnOut ; int[]a=New int[n];  for(inti=1;i<=n;i++) a[i-1]=i; intCount=1;  while(count!=k) {a=Nextpermutation (a); Count++; }         for(inti=0;i<a.length;i++) out+=A[i]; returnOut ; }

Later thought, found that there is a simple method, the advantage of this problem is not to list all the arrangement, and do not need to know all the arrangement before this arrangement, Leetcode to the tag is backtracking, at the beginning really gave me to go in, and later found that in fact can be guessed out of this K-ranked what , no backtracking is required (the reason is that the n elements in the collection are from small to large, that is, from a few of the 1...N). As you can imagine, the total number of n elements is n! , n-1 words are (n-1)!. So for the K-permutation, we can fully know that this permutation is prefixed with that number, which is 1...N, the nth number of k/(n-1)!. Similarly, you can know the number of the second prefix is that (at this time k=k% (n-1)! )...... Until K%x!=0

  PublicString Getpermutation (intNintk) {String out=NewString (); if(n==0)returnOut ; intP=1; List<integer>l=NewArraylist<integer>();  for(inti=1;i<n;i++) {
p=p*i;
L.add (i);
} l.add (n);
ints=k/Q; inty=k%p; intT=n-1; while(y!=0) { out+=L.get (s); L.remove (L.indexof (L.get (s)); K=y; P=p/T; T--; S=k/p; Y=k%Q; } out+=l.get (s-1); //Why S-1? Since the remainder is already 0, the equivalent of the largest permutation of the number that we should prefix is L.get (s-1) L.remove (L.indexof (S-1))); for(intI=l.size () -1;i>=0;i--) out+=L.get (i); The maximum number of digits that can be used to make up the remaining number in the list, as defined by the prefixreturnOut ; }

Method should have a lot, here just see these several questions, so a little summed up a bit, not to, please point out, or there is a better way, please advise!

A series of collations on permutation problems

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.