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 and use only constant 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
AC代码
void sort(vector<int> &v, int begin, int end) {
for (int i = begin; i < end; ++i)
for (int j = i + 1; j <= end; j++)
if (v[i] > v[j]) swap(v[i], v[j]);
}
class Solution {
public:
void nextPermutation(vector<int> &nums) {
bool f = true;
for (int i = nums.size() - 1; i > 0; --i) {
int start, new_start;
if (nums[i] > nums[i - 1]) {
start = i - 1;
while (i < nums.size() && nums[i] > nums[start]) i++;
new_start = i - 1;
swap(nums[start], nums[new_start]);
sort(nums, start + 1, nums.size() - 1);
f = false;
break;
}
}
if (f) {
for (int i = 0; i < nums.size() / 2; ++i)
swap(nums[i], nums[nums.size() - 1 - i]);
}
}
};
总结
1、人搞不来的事情计算机也搞不来,大部分时间用来手算下一个排序
2、思路:从右往左找后一个数字大于前一个数字的位置start,再往右找一个new_start位置,start和new_start之间的数字均大于start,new_start之后的数字均小于start,因为start之后的数字肯定是降序排列,然后交换start和new_start,最后对start位置之后的子数列进行顺序排列。
3、要求空间复杂度为1,只想到了简单的冒泡