A full array of non-recursive output 1-n

Source: Internet
Author: User
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) 

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.