# [31. Next Permutation](https://leetcode.com/problems/next-permutation/) # 思路 题意就是实现标准库里的next_permutation函数(不考虑自定义comp的情况)。 我们先来看看这个函数,以后可以直接用: > Transforms the range [first, last) into the next permutation from the set of all permutations that are lexicographically ordered with respect to operator< or comp. Returns true if such permutation exists, otherwise transforms the range into the first permutation (as if by std::sort(first, last)) and returns false. `bool next_permutation (first, last)`返回的是bool型,如果已经是最后一个排列了则返回false并将数组变成第一个排列(即按照从小到大排好序);否则返回true并将数组变成下一个排列。 此外还可以传入`comp`参数: `next_permutation (first, last, comp)`这样就可以自定义数组的大小规则。 下面来分析一下如何实现: 首先应该知道何为下一个排列,若当前排列组成的数为A,则下一个排列组成的数B就是刚好比A大(即没有另外一个排列组成的数C满足A& nums) { int len = nums.size(); int i, j; for(i = len - 1; i > 0; i--){ if(nums[i] > nums[i - 1]) break; } if(i == 0) { // 已经是最后一个排列时,需要单独考虑。 reverse(nums.begin(), nums.end()); return; } for(j = len - 1; j >= i; j--){ if(nums[j] > nums[i - 1]) break; } swap(nums[j], nums[i-1]); // 用swap击败99%, 若按照下面代码手动实现则击败16% // int tmp = nums[j]; // nums[j] = nums[i - 1]; // nums[i - 1] = tmp; reverse(nums.begin() + i, nums.end()); } }; ```