题目地址:
https://leetcode.com/problems/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).
求下一个组合数。
分析
http://blog.youkuaiyun.com/ljiabin/article/details/41956813
http://www.xuebuyuan.com/1387903.html
1.因为降序序列是没法变的更大的,所以从后往前找到第一个升序对的位置。
2.然后就存在调整大小排列顺序的可能,从后往前找到比当前位置大的元素,交换之。
3.当前位置后面的元素还是降序排列,将他们反转得到最小顺序排列。其实就是原来当前位置元素后面是最大的排列,而交换后的新元素之后是最小的排列,他们就是相邻的顺序。
4.当不存在升序,则当前排列是最大排列,只要旋转整个序列变成最小排列。
代码
https://leetcode.com/problems/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).
求下一个组合数。
分析
http://blog.youkuaiyun.com/ljiabin/article/details/41956813
http://www.xuebuyuan.com/1387903.html
1.因为降序序列是没法变的更大的,所以从后往前找到第一个升序对的位置。
2.然后就存在调整大小排列顺序的可能,从后往前找到比当前位置大的元素,交换之。
3.当前位置后面的元素还是降序排列,将他们反转得到最小顺序排列。其实就是原来当前位置元素后面是最大的排列,而交换后的新元素之后是最小的排列,他们就是相邻的顺序。
4.当不存在升序,则当前排列是最大排列,只要旋转整个序列变成最小排列。
代码
class Solution {
public:
void nextPermutation(vector<int>& nums) {
for(int i=nums.size()-1;i>=1;i--){ //1
if(nums[i-1]<nums[i]){ //1
for(int j=nums.size()-1;j>=i;j--){ //2
if(nums[j]>nums[i-1]){ //2
swap(nums[j],nums[i-1]); //2
break;
}
}
reverse(nums.begin()+i,nums.end()); //3
return;
}
}
reverse(nums.begin(),nums.end()); //4
}
};
本文详细解析了LeetCode上的下一个排列算法题。通过四个步骤实现:寻找升序对、交换元素、反转子序列、处理全降序情况。文章提供了完整的C++代码实现,并附带详细的解释。
423

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



