forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
82cb9ab
commit ab9a9bd
Showing
2 changed files
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test next_permutation.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
|
||
static void reverse(int *a, int size) | ||
{ | ||
int left = 0; | ||
int right = size - 1; | ||
while (left < right) { | ||
int tmp = a[left]; | ||
a[left] = a[right]; | ||
a[right] = tmp; | ||
left++; | ||
right--; | ||
} | ||
} | ||
|
||
void nextPermutation(int* nums, int numsSize) { | ||
if (numsSize <= 1) { | ||
return; | ||
} | ||
|
||
int *p = nums + numsSize - 1; | ||
int *q = nums + numsSize - 1; | ||
|
||
while (p != nums && *(p - 1) >= *p) { | ||
p--; | ||
} | ||
|
||
if (p != nums) { | ||
int n = *(p - 1); | ||
while (*q <= n) { | ||
q--; | ||
} | ||
|
||
int tmp = *q; | ||
*q = *(p - 1); | ||
*(p - 1) = tmp; | ||
} | ||
reverse(p, numsSize - (p - nums)); | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
if (argc <= 1) { | ||
fprintf(stderr, "Usage: ./test ...\n"); | ||
exit(-1); | ||
} | ||
|
||
int i; | ||
int *nums = malloc(sizeof(int)); | ||
for (i = 0; i < argc - 1; i++) { | ||
nums[i] = atoi(argv[i + 1]); | ||
} | ||
|
||
nextPermutation(nums, argc - 1); | ||
|
||
for (i = 0; i < argc - 1; i++) { | ||
printf("%d", nums[i]); | ||
} | ||
putchar('\n'); | ||
|
||
return 0; | ||
} |