This very interesting topic out of the self-knowledge of http://www.zhihu.com/question/24905007/answer/29414497, ranked first friend of the answer with Python concise give the code and answer, wasted I used C + + to tinker for a half day ...
But also can not be regarded as white do, still have a lot of harvest.
First, describe the problem-solving idea accurately:
The essence of this topic is the calculation arrangement:
Define a function permutation (n.m): select M from the n number to make a full arrangement
What we're trying to figure out is
1.σpermutation (9,i) (I from 1 to 9)
The result equals 3024+15120+60480+181440+362880+362880=985824.
2. Then exclude special cases:
13 or 31 appears before 2
17 or 71 appears before 4
19 or 91 appears before 5
37 or 73 appears before 5
79 or 97 appears before 8
28 or 82 appears before 7
46 or 64 appears before 5
The following analysis from scratch:
At first glance, this must be a permutation problem, but there are two easy problems to encounter:
1. But what we generally achieve is all-in-one, so the first question is how to arrange it by a fully arranged calculation.
2. There is also a problem, the majority of the implementation of the full array does not really implement the arrangement, just with the help of recursive stack to achieve the output of all permutations, this difference is very large, we just output is not enough, we should have each record down, and then to exclude.
How to solve the first problem:
After a few attempts, I turned to STL and found that there was only one next_permutation in the STL (the next in the dictionary order), and did not implement normal permutations and combinations.
This prompts me: Since the standard library provides only one full arrangement, the description arrangement can easily be obtained from the full array, in fact this is also consistent with our intuition, verified and analyzed:
I think this is the problem:
For the full arrangement of the dictionary order, we require next_permutation (n,m) to use Next_permutation (n)//full permutation function
The steps are as follows:
l REVERSE the container [m,n] and ask for next_permutation;
L at this time [0,m] is the next_permutation
The principle is also very simple, is the use of the characteristics of the dictionary sequence, why this can be done, in fact, because when we do the full array of information is the largest, we can naturally analyze the size of the smaller arrangement
Second question:
Since my own previous implementation of the full permutation function can directly save all the results in a vector, so there is no such a problem. This is not an algorithm problem, it is a design problem, but the problem can also be very complex, depending on the implementation of the full permutation function.
Show Python Code First: (source is the above URL, I have some changes to its name, easy to understand)
#python
fromItertoolsImport*Impossible= {' -':'2',' $':'5',' -':'8',' -':'4',' -':'5',' the':'6',' +':'5','Panax Notoginseng':'5',' to':'2',' -':'5',' the':'8',' in':'4',' the':'5',' the':'6',' the':'5',' the':'5'}defCount_unlock_screen (): Bucket= Chain (* (Permutations ('123456789'I forIinchRange (4, 10)) Count=0 forIinchBucket:striter="'. Join (i) forKey, ValueinchImpossible.items ():ifKeyinchStriter andValue not inchStriter[:striter.find (Key)]: Break Else: Count+ = 1returnCountPrint(Count_unlock_screen ())
#include <iostream>#include<string>#include<algorithm>using namespacestd;BOOLLegalstringLeftstringRightstringMidstring&a) { stringTest1 = left +Right ; stringTest2 = right +Left ; string:: Size_type p1 =A.find (test1); string:: Size_type P2 =A.find (test2); string:: Size_type q =A.find (mid); if((P1! =string:: NPOs) && (q = =string:: NPOs)) return false; if((P2! =string:: NPOs) && (q = =string:: NPOs)) return false; if((P1! =string:: NPOs) && q >p1)return false; if((P2! =string:: NPOs) && q >p2)return false; return true;}BOOLIs_legal (string&a) { string:: Size_type p =string:: NPOs; stringOne"1");stringBoth ("2");stringThree ("3"); stringFour"4");stringFive"5");stringSix"6"); stringSeven"7");stringEight"8");stringNine"9"); if((!legal (one, three, B, a)) | | (!legal (one, seven, four, a)) | | (!legal (one, nine, five, a)) | | (!legal (three, seven, Five, a)) | | (!legal (three, nine, six, a)) | | (!legal (seven, nine, eight, a)) | | (!legal (eight, Five, a)) | | (!Legal (four, six, Five, a))) return false; Else return true;}
voidSwapChar&index1,Char&index2) { Chartemp =index1; Index1=Index2; Index2=temp;}//the next in full alignmentBOOLNext_permutation (string&a) { inti =0; intSize =a.size (); for(i = size-2; I >=0; i--)//find the first place to meet A[i] < a[i+1] from size I { if(A[i] < A[i +1]) Break; } if(i = =-1)//after the search is over, if I=-1 indicates that the current a array has reached the maximum of the dictionary order { return true; } intj = i +1;//J used to traverse the element between I---n intMin_larger = j;//Min_larger Storage i---n satisfies a[min_larger] > A[j] The smallest, due to the previous I cycle to know a[i+1] must be greater than a[i]//Therefore, Min_larger is initialized to i+1 while(J < size && A[j] >A[i]) { if(A[min_larger] >A[j]) Min_larger=J; J++; } swap (A[i], A[min_larger]); string:: Iterator KB = A.begin () + i +1; string:: Iterator ke =A.end (); Reverse (KB, KE); return false;}//calculate the next number of permutationsBOOLNext_k_permutation (string&a,intLengthstring&result) {Reverse (A.begin ()+length, a.end ()); if(!Next_permutation (a)) { stringSS (A,0, length); Result=SS; return true; } return false; }voidCount_all (string&a) { intLength =a.size (); intCount =0; while(Length >=4) {sort (A.begin (), A.end ()); Count++; stringresult; while(Next_k_permutation (A, Length,result)) {if(Is_legal (Result)) {count++; } } --length; } cout<< Count <<Endl;}intMain () {strings ="123456789"; Count_all (s); System ("Pause"); return 0;}
Python code runs really fast, and for such a large number of calculations, results can be given within seconds. The Python data structure and library optimization is still good, compared to my own implementation of the C + + solution is significantly faster, obviously not to say that C + + efficiency is low, but C + + for string processing is really very troublesome, I do not have too much targeted optimization, so the operation is relatively slow, but the result is correct.
This question is still very interesting, but in fact it is quite difficult, try to use Mathematics direct hand calculation but give up, the elimination is more troublesome, or with the help of computer!