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
分析及題解:這道題是尋找給定的一列數的下一個排列, 如果給定的數是該列數的最后一個排列, 則該列數的下一個排列是該列數的第一個排列. 如6, 5, 4, 3, 2, 1
是該列數的最后一個排列, 則下一個排列是1, 2, 3, 4, 5, 6
, 也即是該列數的第一個排列.
解決這道題的重點是找到排列數的下一個排列數的生成規律, 對于1, 2, 6, 5, 4, 3
的下一個排列數為1, 3, 2, 4, 5, 6
. 規律如下:
從后往前尋找第一個從后往前不是遞增的數, 用index
指向它, 此處是2, 即index = 1
, 因為2小于6, 不滿足從后往前遞增. 然后從后往前尋找第一個大于index
指向的數, 用p
指向該數, 此處為3, 即p = 5
. 交換index
和p
指向的數, 最后將index
后的數逆序即可. 如果找到的index
為0, 則直接逆序整個數列即可. 整個過程中需要三次遍歷, 算法復雜度是O(3n)即O(n).
過程如下:
1, 2, 6, 5, 4, 3
--> 1, 3, 6, 5, 4, 2
--> 1, 3, 2, 4, 5, 6
.
代碼:
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if(nums.size() < 2) return;
int index = nums.size() - 2;
while(index > 0 && nums[index] >= nums[index+1]) {
// 找到第一個從后往前數不是遞增序的數
index--;
}
int p = nums.size() - 1;
while(p > index && nums[p] <= nums[index]) {
// 從后往前找到第一個大于index所指的數
p--;
}
int tmp;
if(p != index) { // nums不是最后一個排列
// 交換p和index所指向的數據
tmp = nums[p];
nums[p] = nums[index];
nums[index] = tmp;
index++;
}
// 逆序index之后的數
p = nums.size() - 1;
while(index < p) {
tmp = nums[index];
nums[index] = nums[p];
nums[p] = tmp;
index++;
p--;
}
}
};