您的位置:首页 > 其它

LeetCode 31. Next Permutation(下一组排列)

2018-03-19 16:20 423 查看
题目描述:
    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


分析:
    题意:给定一个整型数组,根据字典序,返回它的下一个排列(如果当前给出的是最后一个排列,返回第一个排列)。
    思路:这是一道经典的排列组合题,已经存在固定的算法去解决这个问题(Next lexicographical permutation algorithm)。
    假设数组为array,长度为n,步骤如下:
    ① 首先找到最大的坐标i,使得array[i - 1] < array[i]。
    ② 然后找到最大的坐标j,满足j大于等于i,且array[j] > array[i - 1]。
    ③ 交换array[j]和array[i - 1]的元素。
    ④ 将array[i]和array[n - 1]之间的元素反转。
    时间复杂度为O(n)。
    如果有人直接调用C++库函数next_permutation,我竟无言以怼。
代码:
#include <bits/stdc++.h>

using namespace std;

/*
// Accepted
class Solution {
public:
void nextPermutation(vector<int>& nums) {
next_permutation(nums.begin(), nums.end());
}
};
*/

class Solution {
private:
void reverse(vector<int>& vec, int start, int end){
for(int i = start; i <= (start + end) / 2; i++){
swap(vec[i], vec[start + end - i]);
}
}

public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
// Exceptional Case:
if(n <= 1){
return;
}
int i = n - 2;
while(i >= 0 && nums[i] >= nums[i + 1]){
i--;
}
if(i == -1){
reverse(nums, 0, n - 1);
return;
}
int j = i + 1;
while(j <= n - 1 && nums[j] > nums[i]){
j++;
}
// swap
swap(nums[i], nums[j - 1]);
reverse(nums, i + 1, n - 1);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C LeetCode Permutation