Leetcode31题——《下一个排列》
读题思路:这道题其实就是求比所给排列大一丢丢的数字,例如:nums = [1,2,3],那么就是123<132<213<231<312<321,也就是当 “1,2,3” 的下一个排列就是“1,3,2”,“1,3,2”的下一个排列就是 “2,1,3”,同理,注意到最后一个排列也就是最大的数的时候 “3,2,1”的下一个排列就是开头的 “1,2,3”了。所以最直接的做法就是把数组中的数字的可能的排列都列出来,然后从小到大排列,然后找比它大一点的排列就可以了。我感觉这道题还是可以用回溯做出来,之后回头来看看这个代码。
参考思路和代码:
参考链接:下一个排列算法详解:思路+推导+步骤,看不懂算我输! - 下一个排列 - 力扣(LeetCode)
void nextPermutation(vector<int>& nums) {
int n = nums.size();
if (n <= 1)
{
return;
}
int i = n - 2, j = n - 1, k = n - 1;
while (i >= 0 && nums[i] >= nums[j])
{
--i;
--j;
}
if (i >= 0)
{
while (nums[i] >= nums[k]) --k;
swap(nums[i], nums[k]);
}
reverse(nums.begin() + j, nums.end());
}