52 下一个排列

原题网址:https://www.lintcode.com/problem/next-permutation/description

描述

给定一个整数数组来表示排列,找出其之后的一个排列。

排列中可能包含重复的整数

您在真实的面试中是否遇到过这个题?  

样例

给出排列[1,3,2,3],其下一个排列是[1,3,3,2]

给出排列[4,3,2,1],其下一个排列是[1,2,3,4]

思路:如果做过全排列字典序,那么相较于上一个排列,下一个排列要容易理解一些。

1 首先,从右向左寻找递增序列的下一个位置(递增结束位置),即nums【i】<nums【i+1】,该位置为第一个变位。找到了,转2,否则返回翻转后的整个数组;

2 在 i+1~end 中从右向左寻找递增序列中第一个大于nums【i】的元素位置k,交换 t 与 k 处的元素;

3 翻转i+1 ~ end 部分的元素。

AC代码:

class Solution {
public:
    /**
     * @param nums: A list of integers
     * @return: A list of integers
     */
    vector<int> nextPermutation(vector<int> &nums) {
        // write your code here
        vector<int> result=nums;
    int n=nums.size();
    int i=-1;
    for (int j=n-2;j>=0;j--)
    {
        if (result[j]<result[j+1])
        {
            i=j;
            break;
        }
    }
    
    if (i!=-1)
    {
        int k;
        for (int j=n-1;j>i;j--)
        {
            if (result[j]>result[i])
            {
                k=j;
                break;
            }
        }
        swap(result[i],result[k]);
        reverse(result.begin()+i+1,result.end());
    }
    else
    {
        reverse(result.begin(),result.end());
    }
    return result;
    }
};

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9106105.html
52