[LeetCode] Next Permutation
Well, in fact the problem of next permutation has been studied long ago. From the Wikipedia page, in the 14th century, a man named Narayana Pandita gives the following classic and yet quite simple algorithm (with minor modifications in notations to fit the problem statement):
- Find the largest index
k
such thatnums[k] < nums[k + 1]
. If no such index exists, the permutation is sorted in descending order, just sort it again in ascending order and we are done. For example, the next permutation of[3, 2, 1]
is[1, 2, 3]
. - Find the largest index
l
greater thank
such thatnums[k] < nums[l]
. - Swap the value of
nums[k]
with that ofnums[l]
. - Reverse the sequence from
nums[k + 1]
up to and including the final elementnums[nums.size() - 1]
.
Quite simple, yeah? Now comes the following code, which is barely a translation.
Well, a final note here, the above algorithm is indeed powerful --- it can handle the cases of duplicates! If you have tried the problems Permutations and Permutations II, then the following function is also useful. Both of Permutations and Permutations II can be solved easily using this function. Hints: sort nums
in ascending order, add it to the result of all permutations and then repeatedly generate the next permutation and add it ... until we get back to the original sorted condition. If you want to learn more, please visit this solution and that solution.
1 void nextPermutation(vector<int>& nums) { 2 int k = -1; 3 for (int i = nums.size() - 2; i >= 0; i--) { 4 if (nums[i] < nums[i + 1]) { 5 k = i; 6 break; 7 } 8 } 9 if (k == -1) { 10 sort(nums.begin(), nums.end()); 11 return; 12 } 13 int l = -1; 14 for (int i = nums.size() - 1; i > k; i--) { 15 if (nums[i] > nums[k]) { 16 l = i; 17 break; 18 } 19 } 20 swap(nums[k], nums[l]); 21 reverse(nums.begin() + k + 1, nums.end()); 22 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步