-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNextPermutation.java
More file actions
63 lines (52 loc) · 1.58 KB
/
NextPermutation.java
File metadata and controls
63 lines (52 loc) · 1.58 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
//https://leetcode.com/problems/next-permutation/description/
public class NextPermutation {
public static void main(String[] args) {
NextPermutation np = new NextPermutation();
int[] nums = new int[]{1,2,3};
for (int i = 1; i <= 6; i++) {
np.nextPermutation(nums);
np.printArray(nums);
}
nums = new int[]{1};
for (int i = 1; i <= 2; i++) {
np.nextPermutation(nums);
np.printArray(nums);
}
nums = new int[]{1,1,5};
for (int i = 1; i <= 4; i++) {
np.nextPermutation(nums);
np.printArray(nums);
}
}
public void printArray(int[] nums) {
for (int n : nums)
System.out.print(n + " ");
System.out.println();
}
public void nextPermutation(int[] nums) {
// let i be the largets index such that a_i < a_i+1
int i = nums.length - 2;
while (i >= 0 && nums[i] >= nums[i+1]) {
i--;
}
if (i != -1) {
// find the largest index j such that a_i < a_j (note: j >= i+1 )
int j = nums.length-1;
while (nums[i] >= nums[j])
j--;
// swap a_i and a_j
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
int left = i+1;
int right = nums.length-1;
while (left < right) {
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}