LeetCode#31. Next Permutation

topic:

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

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

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

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

Title:

This question is asking us to find the next permutation of a sequence, that is, the closest permutation in ascending order. If the sequence is regarded as an integer, it is to find the next number with the same number as the integer.

At the beginning, when I was doing this, an algorithm that came to my mind was to first replace the entire sequence with an integer, and then start accumulating from this integer, and terminate when the same number as the integer number appears, and take out this new number from high to low. The individual digits of the integer are the answer, but this answer, unfortunately, has timed out, that is, when the sequence is long and the number distribution is not very uniform, it takes many accumulations to find the answer, so we have to think new algorithm to solve this problem.

A new algorithm is as follows:

1. If this sequence is the largest of the current numbers, just return the smallest sequence.

2. Traverse this sequence from back to front, jump out of the loop when the first a[i] < a[i+1] is found, record the position of i at this time, and denote it as k

3. Swap the last number in the sequence with k.

4. Perform the reverse operation on k+1 to the last number, and the result obtained in this way is correct.

Let me give an example: for example 2431

First, the first a[i] < a[i+1] appears at the position of 2, that is, i = 0, then swap 2 and 1, that is, 1432, and then transpose 432 to get 234, and finally the correct result That is 1234.

A C++ code is as follows:

#include<iostream>
#include<vector>
#include<iterator>

using namespace std;

class Solution {
public:
    void nextPermutation(vector<int>& nums) {
    	int n = nums.size()-1;
    	bool is = false;
        for(int i = 0; i < n; i++) {
			if(nums[i] < nums[i+1]) {
				is = true;
				break;
			}
		}
		if (is == false) {
			reverse(nums.begin(),nums.end());
		} else {
			int k;
			for(int i = n-1; i >= 0; i--) {
				if(nums[i] < nums[i+1]) {
					k = i;
					break;
				}
			}
			int j;
			for(int i = n; i > k; i--) {
				if(nums[i] > nums[k]) {
					j = i;
					break;
				}
			}
			swap(nums[k],nums[j]);
			reverse(nums.begin()+k+1,nums.end());
		}
    }
    void swap(int &a, int &b) {
    	int temp;
    	temp = a;
    	a = b;
    	b = temp;
	}
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325421477&siteId=291194637
Recommended