forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0046-permutations.c
44 lines (37 loc) · 1.26 KB
/
0046-permutations.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
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void backtrack(int* nums, int numsSize, int** result, int* returnSize, int* current, int index) {
if (index == numsSize) {
result[*returnSize] = (int*)malloc(numsSize * sizeof(int));
for (int i = 0; i < numsSize; i++) {
result[*returnSize][i] = current[i];
}
(*returnSize)++;
return;
}
for (int i = index; i < numsSize; i++) {
swap(&nums[i], &nums[index]);
current[index] = nums[index];
backtrack(nums, numsSize, result, returnSize, current, index + 1);
swap(&nums[i], &nums[index]);
}
}
int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes) {
int totalPermutations = 1;
for (int i = 1; i <= numsSize; i++) {
totalPermutations *= i;
}
int** result = (int**)malloc(totalPermutations * sizeof(int*));
int* current = (int*)malloc(numsSize * sizeof(int));
*returnSize = 0;
*returnColumnSizes = (int*)malloc(totalPermutations * sizeof(int));
backtrack(nums, numsSize, result, returnSize, current, 0);
for (int i = 0; i < totalPermutations; i++) {
(*returnColumnSizes)[i] = numsSize;
}
free(current);
return result;
}