solution.cpp 795 字节
Newer Older
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
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static char *getPermutation(int n, int k)
{
	int i;
	char *result = malloc(n + 1);
	bool *used = malloc(n * sizeof(bool));
	memset(used, false, n * sizeof(bool));
	int total = 1;
	for (i = 1; i <= n; i++)
	{
		total *= i;
	}
	k = k - 1;
	for (i = 0; i < n; i++)
	{
		total /= (n - i);
		int gid = k / total;
		k %= total;
		int x = -1;
		int count = 0;
		while (count <= gid)
		{
			x = (x + 1) % n;
			if (!used[x])
			{
				count++;
			}
		}
		used[x] = true;
		result[i] = x + 1 + '0';
	}
	result[n] = '\0';
	return result;
}
int main(int argc, char **argv)
{
	if (argc != 3)
	{
		fprintf(stderr, "Usage: ./test n, k\n");
		exit(-1);
	}
	printf("%s\n", getPermutation(atoi(argv[1]), atoi(argv[2])));
	return 0;
}