1. 程式人生 > >31.[LeetCode] Next Permutation下一個排列

31.[LeetCode] Next Permutation下一個排列

如果給定陣列是降序,則說明是全排列的最後一種情況.

舉個例子[1]:
1  2  7  4  3  1
下一個排列是:
1  3  1  2  4  7
具體過程(核心思想):如果從末尾往前看,數字逐漸變大,到了2時才減小的,然後我們再從後往前找第一個比2大的數字,是3,那麼我們交換2和3,再把此時3後面的所有數字轉置一下即可,步驟如下:
1  2  7  4  3  1

1  2  7  4  3  1

1  3  7  4  2  1

1  3   1  2  4  7

c++ code :

class Solution {
public:
	void nextPermutation
(vector<int>& nums) { int n = nums.size(); int i = n - 2, j = n - 1; while (i >= 0 && nums[i] >= nums[i + 1])i--; if (i >= 0)//除了是全降序即i=-1不考慮 { while (nums[j] <= nums[i])j--; swap(nums[j], nums[i]); } reverse(nums.begin()+i+1,nums.end());//都要翻轉 } };

[1]

https://www.cnblogs.com/grandyang/p/4428207.html