How to find the next sequence: next_permutation

Source: Internet
Author: User

There is a sequence of 1 6 3 5 4 2 end (one number after the last number is recorded as end)

 

What is the next arrangement of his Lexicographic Order?

 

1. we can find the first descending order (x, y) from the back, because [y, end) is already descending, in [y, end) if there is no number in it for exchange, this sequence can be larger. On the contrary, it will become smaller. therefore, [y, end) cannot be larger than [x, end.

 

That is, 1 63 54 2, (3, 5) indicates the (x, y) pair of this sequence.

 

2. How can we minimize the value of the [x, end) sequence, that is, "only a little bigger?

We only need to find a number that is a little larger than X and replace it with it, and satisfy this number is the smallest of the optional numbers.

Then we find the first number greater than X as Z, and exchange x Z.

 

That is, first find 4, 1 63542

Switch 3, 4, 1 6 again4532

The result is: 1 6 4 5 3 2.

 

3. Finally, the [y, end) sequence must be sorted in descending order. We will change it to a minimum and sort it in descending order so that it can be sorted in ascending order.

That is, after descending order, 1 6 42 3 5

 

Believe that you are smart, you must have understood -_-

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.