From ab9a9bd0ca7cbfe312eab6012b75cb17e4953d17 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Thu, 20 Jul 2017 09:19:49 +0800 Subject: [PATCH] Next permutation Signed-off-by: begeekmyfriend --- 031_next_permutation/Makefile | 2 + 031_next_permutation/next_permutation.c | 63 +++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 031_next_permutation/Makefile create mode 100644 031_next_permutation/next_permutation.c diff --git a/031_next_permutation/Makefile b/031_next_permutation/Makefile new file mode 100644 index 0000000..437189e --- /dev/null +++ b/031_next_permutation/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test next_permutation.c diff --git a/031_next_permutation/next_permutation.c b/031_next_permutation/next_permutation.c new file mode 100644 index 0000000..19b0afe --- /dev/null +++ b/031_next_permutation/next_permutation.c @@ -0,0 +1,63 @@ +#include +#include + +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; +}