Leetcode:Next Permutation 下一个排列

Next Permutation

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,31,3,2
3,2,11,2,3
1,1,51,5,1

 

解题分析:

step1. 从后往前遍历,找到第一个 升序的相邻元素,即 num.at(i) < num.at(i+1)

          如果遍历之后 i的值为-1,即 数组中所有相邻都逆序,即数组降序,此时只需要 reverse数组,直接返回即可

step2. 再次从后往前遍历,找到第一个 num.at(k) > num.at(i) 的值

          如果 step1没有全逆序直接返回,那么这一步的 k值一定 大于 i,因为存在相邻的升序对

step3. swap(num.at(i), num.at(k))

step4. 将 num位于 坐标 i 以后的元素反转

class Solution {
public:
    void nextPermutation(vector<int> &num) {
        if (num.size() < 2) return;
        int i = 0;
        int k = 0;
        for (i = num.size() - 2; i >= 0; --i) {
            if (num.at(i) < num.at(i+1)) {
                break;
            }
        }
        if (i < 0) {
            reverse(num.begin() + i + 1, num.end());
            return;
        }
        
        for (k = num.size() - 1; k > i; --k) {
            if (num.at(k) > num.at(i)) {
                break;
            }
        }
        swap(num.at(i), num.at(k));
        reverse(num.begin() + i + 1, num.end());
    }
};

 

你可能感兴趣的:(LeetCode)