The following small series for everyone to bring a non-recursive output 1-n the full array of instances (recommended). Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
NetEase Game pen question algorithm one, can use C++,java,python, because Python code quantity is small, so I choose Python language.
The overall idea of the algorithm is from ... N This arrangement begins, calculating the next arrangement until the output n,n-1,...... Until 1
So how do you calculate the next permutation for a given arrangement?
Consider this sequence of [2,3,5,4,1], looking forward to the first pair of ascending contiguous numbers, that is, 3, 5. Then 3 is the replacement number, and the 3 position is the replacement point.
Swap 3 and the replacement point behind the minimum number of 3, here is 4, get [2,4,5,3,1]. Then swap the first and last number after the replacement point, that is, Exchange 5, 1. We get the next sequence [2,4,1,3,5]
The code is as follows:
def Arrange (pos_int): #将1-N into the list templist, convenient handling templist = [i+1 for i in Range (Pos_int)] Print (TE mplist) while templist! = [Pos_int-i for i in Range (Pos_int)]: For I in Range (pos_int-1,-1,-1): if (templist[i]> ; Templist[i-1]): #考虑tempList [i-1] The smallest of the elements behind it, swapping. Minmax = min ([k for K in Templist[i::] If k > templist[i-1]]) #得到minmax在tempList中的位置 index = Templist.ind EX (MINMAX) #交换 temp = templist[i-1] templist[i-1] = Templist[index] templist[index] = Temp #再交换tempList [i] and last element, get the next permutation of templist temp = templist[i] templist[i] = templist[pos_int-1] Temp LIST[POS_INT-1] = temp print (templist) Breakarrange (5)