-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNo.31. Next Permutation
47 lines (43 loc) · 1.08 KB
/
No.31. Next Permutation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//Code
class Solution {
public:
void nextPermutation(vector<int>& nums)
{
if(nums.size()==0||nums.size()==1)
return ;
next(nums,1);
return ;
}
void next(vector<int> & nums, int n) // find next arage
{
int len=nums.size();
if(n==len) //to the head,
{
rev(nums);
return ;
}
else if(nums[len-n-1]>=nums[len-n]) //
{
n++;
next(nums,n);
}
else
{ int i;
for(i=len-1;i>=len-n;i--) //find the smallest in last n nums;
{
if(nums[i]>nums[len-n-1])
break;
}
int x=nums[len-n-1]; //swap
nums[len-n-1]=nums[i];
nums[i]=x;
sort(nums.begin()+len-n,nums.end()); rearrage
return ;
}
}
void rev(vector<int> & nums) //no,reverse
{
sort(nums.begin(),nums.end());
return ;
}
};