forked from lolosssss/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path31_next_permutation.c
76 lines (64 loc) · 1.41 KB
/
31_next_permutation.c
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
64
65
66
67
68
69
70
71
72
73
74
75
76
/**
* Description : 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).
* Author : Evan Lau
* Date : 2016/03/20
*/
#include <stdio.h>
void reverse(int *nums, int begin, int end)
{
int tmp;
while (begin < end)
{
tmp = nums[begin];
nums[begin] = nums[end];
nums[end] = tmp;
begin++;
end--;
}
}
void nextPermutation(int* nums, int numsSize)
{
int i;
int tmp;
int mark = -1;
for (i = numsSize - 2; i >= 0; i--)
{
if (nums[i] < nums[i + 1])
{
mark = i;
break;
}
}
if (mark == -1)
{
reverse(nums, 0, numsSize - 1);
return;
}
for (i = numsSize - 1; i>= mark; i--)
{
if (nums[i] > nums[mark])
{
tmp = nums[i];
nums[i] = nums[mark];
nums[mark] = tmp;
break;
}
}
reverse(nums, mark + 1, numsSize - 1);
}
int main(void)
{
int arr[] = {1, 1, 5};
int size = 3;
nextPermutation(arr, size);
for (int i = 0; i < size; i++)
{
printf("%d -> ", arr[i]);
}
printf("null\n");
return 0;
}