題目:
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