1. From right to left, find the first num[i] < num[i+1];
2. From right to left, find the smallest element such that num[j] > num[i]
3. Sort the num from i to length
public void nextPermutation(int[] num) {
if (num == null) return;
int i = num.length - 2;
while (i >= 0 && num[i] >= num[i+1]) i--;
if (i < 0) {
Arrays.sort(num);
return;
} else {
for (int j = num.length - 1; j>=0; j--) {
if (num[j] > num[i]) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
Arrays.sort(num, i+1, num.length);
return;
}
}
}
}
No comments:
Post a Comment