leetcode31. 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值