31. 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,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

手动实现C++ STL next_permutation函数,源码也是这个思路实现的,详情可见:http://blog.csdn.net/hongchangfirst/article/details/8672183

算法思路:

串1:1 2 5 4 3  

串1:1 2 5 3 4  

->从又开始找第一个分界线,第一个右边大于左边的分界,比如串1,2 5 令i=左边的 2,串2,3 4,i=3

->然后从最右边开始倒着找第一个不小于i的数,即3,串二4

->交换这两个数,

交换后:串1:1 3 5 4 2  

    串1:1 2 5 4 3

->逆转i下标后面的这个子串,不包括i。

交换后:串1:1 3 2 4 5 

    串1:1 2 5 4 3 (不变)

因为找的这个子串就是非递增排序,逆转后其实就是一个非递减序列。

如果找不到这个序列,说明是全排列的最后一个序列,直接逆转即可。

#include <bits/stdc++.h>

using namespace std;


void nextPermutation(vector<int> &num)
{
    int i, j, n = num.size();
    for (i = n - 2; i >= 0; --i)
    {
        if (num[i + 1] > num[i])
        {
            for (j = n - 1; j >= i; --j)
            {
                if (num[j] > num[i]) break;
            }
            swap(num[i], num[j]);
//            cout<<"第一次交换后:";
//            for(int i = 0; i < num.size(); i++)
//            {
//                cout<<num[i]<< " ";
//            }
//            cout<<endl;
            reverse(num.begin() + i + 1, num.end());
//            cout<<"第一次反转后:";
//            for(int i = 0; i < num.size(); i++)
//            {
//                cout<<num[i]<< " ";
//            }
            cout<<endl;
            return;
        }
    }
    //如果没有找到,那么是最后一个序列,直接反转即可。
    reverse(num.begin(), num.end());
}

int main()
{
    freopen("in.txt","r",stdin);
    vector<int> num;
    int n;
    cin>>n;
    while(n--)
    {
        int t;
        cin>>t;
        num.push_back(t);
    }
    nextPermutation(num);
    for(int i = 0; i < num.size(); i++)
    {
        cout<<num[i]<< " ";
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zhangmingzhao/p/7374956.html