[Leetcode] 031. Next permutation (Medium) (C++/python)

Source: Internet
Author: User

Index: [Leetcode] leetcode key index (C++/JAVA/PYTHON/SQL)
Github:https://github.com/illuz/leetcode

031. Next permutation (Medium) links

Title: https://oj.leetcode.com/problems/next-permutation/
Code (GitHub): Https://github.com/illuz/leetcode

Test Instructions

Find the next permutation of a sequence.

Analysis

Can be lazy with the ' next_permutation ' in STL.

The specific algorithm is:

First, from the end of the beginning to look forward to two adjacent elements, so that the first element is I, the second element is II, and meet i<ii ;
Then, from the end of the beginning to search forward, find the first element greater than I, set it to J;
Then, I and J are swapped, and then all elements of the II and later are reversed.

Code

C++:

Class Solution {public:    void Nextpermutation (vector<int> &num) {if (!num.size ()) Return;int idx = num.size ()-2;//1. Find out the last wrong orderwhile (idx >= 0 && num[idx] >= num[idx + 1]) idx--;//2. SWAPIF (idx >= 0) {int i = idx + 1;while (i < num.size () && num[i] > Num[idx]) i++;swap (num[i-1], Num[id x]);} 3. Reversereverse (Num.begin () + idx + 1, num.end ());}};


Python:

Class solution:    # @param num, a list of integer    # @return Nothing (void), does not return anything, modify Num IN-PL Ace instead.    def nextpermutation (self, num):        if not len (num):            return        idx = len (num)-2        # 1. "Find out" the last wrong or Der while        idx >= 0 and Num[idx] >= Num[idx + 1]:            idx-= 1        # 2. Swap        If idx >= 0:            i = idx +  1            While I < Len (num) and num[i] > Num[idx]:                i + = 1            num[i-1], num[idx] = Num[idx], num[i-1]        #  3. Reverse left        , right = idx + 1, len (num)-1 and left        <= right:            Num[left], num[right] = Num[right], Num[left] Left            + = 1 Right-            = 1


[Leetcode] 031. Next permutation (Medium) (C++/python)

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.