"Leetcode" Next permutation problem solving report

Source: Internet
Author: User

Topic

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If Such arrangement is not a possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must is in-place, do not allocate extra memory.

Here is some examples. Inputs is in the left-hand column and its corresponding outputs is in the right-hand column.
1,2,31,3,2
3,2,11,2,3
1,1,51,5,1

Resolution

is actually the displacement generation algorithm Dictionary ordering method to generate the next arrangement of the current arrangement.

Previously written full permutation algorithm "Leetcode" Permutations Problem solving report

The difference is that the whole arrangement above is generated from small to large, and there is no 2nd step in the code.

public class Solution {public void nextpermutation (int[] num) {//1. Find last ascending position pos int pos =-1;                for (int i = num.length-1; i > 0; i--) {if (Num[i] > Num[i-1]) {pos = i-1;            Break }}//2. If there is no ascending order, that is, this number is the largest, then the array is inverted if (pos < 0) {reverse (num, 0, num.length-1            );        Return  }//3. There is an ascending order, then the last position that is larger than the POS is found for (int i = num.length-1; i > pos; i--) {if (Num[i]                > Num[pos]) {int tmp = Num[i];                Num[i] = Num[pos];                Num[pos] = tmp;            Break    }}//4. number reverse (num, pos + 1, num.length-1) after the reverse POS;        public void reverse (int[] num, int begin, int end) {int L = begin, R = end;            while (L < r) {int tmp = num[l];            NUM[L] = Num[r];            NUM[R] = tmp;    l++;        r--; }    }}


"Leetcode" Next permutation problem solving report

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.