难度:medium
描述
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.
思路:寻找组合的下一个,可以用来生成一个串的所有组合,一些场景下很有用的算法:
基本就是从后开始搜索,找到一个前面数值f比后面数值b小的相邻项,再次开始尾端搜索,找到一个比f大的,然后交换数值,再颠倒f后面的数字的顺序。
这样就获得下一个组合,然而如果,从后找到前都没找到前面值比后面小的,说明这是个降序的组合,也就是到头了,这时根据需要返回到头的消息或者是全部颠倒。
代码:
class Solution {
public:
void reverse(vector<int>& nums,int begin){
int pointer = begin;
int* temp = new int[nums.size()-begin];
for (int i = nums.size()-begin-1; pointer < nums.size(); i--){
temp[i] = nums[pointer];
pointer++;
}
for (int i = 0; begin < nums.size(); i++) {
nums[begin] = temp[i];
begin++;
}
delete []temp;
}
void nextPermutation(vector<int>& nums) {
if(nums.size() == 0 || nums.size() == 1) {
return;
}
int f = nums.size()-1;
int b = 0;
while(1){
b = f;
f--;
if (nums[f] < nums[b]){
int s = nums.size()-1;
while(nums[s] <= nums[f]) s--;
int temp = nums[s];
nums[s] = nums[f];
nums[f] = temp;
reverse(nums,b);
return;
}
if (f == 0){
reverse(nums,0);
return;
}
}
}
};
本文介绍了一个中等难度的算法问题——实现下一个排列。该算法用于重新排列数字以形成字典序中更大的排列。若无法形成更大排列,则将数字按升序排列。文章详细解释了解决方案的思路,并提供了一个具体的C++代码实现。
213

被折叠的 条评论
为什么被折叠?



