"Leetcode" Next permutation

Source: Internet
Author: User

Test instructions

Find the next dictionary order

Example 1

Input:123

Generated:123,213,231,312,321

Result: one of the 123 is the next

Example 2

Input:321

Generated:123,213,231,312,321

Result: where 123 is the next 321 ( loop )

Ideas

Any arrangement:a[0],a[1]... A[n]

Find i, meet A[i]<a[i+1], and have a[i+1]>=a[i+2]... >=a[n]

From A[i+1] to a[n] , select the first number smaller than a[i] a[k]

a[i+1 ] to A[n] reverse position after swapping A[i] with A[k]

Then a[0],a[1]... A[n] in the next row column

A[0],a[1]... A[k]a[n]a[n-1]... A[k+1]a[i]a[k-1]a[i+1]

??

Example

Arranged as:236541

Steps

1, from the forward look, to find the first is not in order to increase the number, such as the example of 3, before the 1456 are in turn, note the position p, at this time p=1

2. Discussion of the situation

a, if all are growth in turn, then the arrangement is the last arrangement, the next is the first, as long as the arrangement in reverse order, such as 654321 Next is 123456

b, if p exists, look backward from p , find the first number smaller than him, this example is 1, then the pointer moves back to the number of the previous number, this example is 4, Exchange 3 and 4 of the position, this time for 246531

3, finally the number after the p reverse, that is, 6531 reverse order, get the next sequence 241356

"Leetcode" Next permutation

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.