-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext Permutation.java
More file actions
45 lines (44 loc) · 1.15 KB
/
Copy pathNext Permutation.java
File metadata and controls
45 lines (44 loc) · 1.15 KB
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
import java.util.* ;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
public class Solution
{
public static void Reverse(ArrayList<Integer> permu,int start,int end){
for(int i=start;i<=(start+end)/2;i++){
int temp = permu.get(i);
permu.set(i,permu.get(end-i+start));
permu.set((end-i+start),temp);
}
}
public static void swap(ArrayList<Integer> permu,int i,int j){
int temp = permu.get(i);
permu.set(i,permu.get(j));
permu.set(j,temp);
}
public static ArrayList<Integer> nextPermutation(ArrayList<Integer> permu)
{
// Write your code here.
int i = permu.size()-2 ;
while(i>=0){
if(permu.get(i)<permu.get(i+1)){
break;
}
i--;
}
if(i==-1){
Reverse(permu,0,permu.size()-1);
return permu;
}
int j=permu.size()-1;
while(j>i){
if(permu.get(j)>permu.get(i)){
break;
}
j--;
}
swap(permu,i,j);
Reverse(permu,i+1,permu.size()-1);
return permu;
}
}