地址:http://oj.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).
The replacement must be in-place, do not allocate extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3
→ 1,3,2
3,2,1
→ 1,2,3
1,1,5
→ 1,5,1
http://www.keithschwarz.com/interesting/code/?dir=next-permutation
正好是此题。
大意是:
1. 从数组尾向头找到最大连续升序的序列 x
2. 将序列x起点(数组尾为终点)左边的数(如果有的话),记为y,与该序列中大于y的最小的数交换
3. 将交换后的序列x排序(从小到大)
c++参考代码:
class Solution {
public:
void nextPermutation(vector<int> &num) {
if(num.empty())
return;
int pos = num.size()-1;
while(pos && num[pos]<=num[pos-1])
--pos;
if(!pos)
sort(num.begin(), num.end());
else
{
for(int i = num.size()-1; i>=pos; --i)
if(num[i] > num[pos-1])
{
swap(num[i], num[pos-1]);
break;
}
sort(num.begin()+pos, num.end());
}
}
};
python参考代码:
class Solution:
# @param num, a list of integer
# @return a list of integer
def nextPermutation(self, num):
if not num:
return num
for i in range(len(num)-1,0,-1):
if num[i] > num[i-1]:
for j in range(len(num)-1,i-1,-1):
if num[j] > num[i-1]:
num[i-1], num[j] = num[j], num[i-1]
break
return num[:i] + sorted(num[i:])
return sorted(num)
//what's more, it can also abandon sorting at last. What's amazing is the code below is 20ms+ later than the upper one.//I think there must be some optimizations in STL.//coding two weeks later.
class Solution {public :void nextPermutation ( vector < int > & num ) {if ( num . empty () || num . size () == 1 )return ;int pos = num . size () - 1 ;for (; pos >= 1 ; -- pos ){if ( num [ pos ] > num [ pos - 1 ])break ;}if ( ! pos ){for ( int i = 0 , j = num . size () - 1 ; i < j ; ++ i , -- j )swap ( num [ i ], num [ j ]);}else{for ( int i = num . size () - 1 ; i >= pos ; -- i ){if ( num [ i ] > num [ pos - 1 ]){swap ( num [ i ], num [ pos - 1 ]);break ;}}for ( int j = num . size () - 1 ; j > pos ; -- j , ++ pos )swap ( num [ j ], num [ pos ]);return ;}}};
//Thrid trialclass Solution {public :void nextPermutation ( vector < int > & num ) {if ( num . empty ())return ;int sz = num . size (), pos = 0 ;for ( pos = sz - 1 ; pos >= 1 ; -- pos ){if ( num [ pos ] > num [ pos - 1 ])break ;}if ( ! pos )reverse ( num . begin (), num . end ());else{for ( int i = sz - 1 ; i >= pos ; -- i ){if ( num [ i ] > num [ pos - 1 ]){swap ( num [ i ], num [ pos - 1 ]);break ;}}reverse ( num . begin () + pos , num . end ());}}};