题目:
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 Permutation
解法:求下一个全排列,从后向前找到第一个顺序对,将后者插入前者之前,并反转中间部分。同时可以使用next_permutation库函数直接解决。时间O(n^2)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i, j;
for (i = nums.size() - 2; i >= 0; --i) {
if (nums[i] < nums[i + 1]) break;
}
for (j = nums.size() - 1; j >= i ; --j) {
if (nums[j] > nums[i]) break;
}
if (i >= 0) {
swap(nums[i], nums[j]);
}
reverse(nums.begin() + i + 1, nums.end());
return;
}
};
Runtime: 12 ms