-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPermutations.c
44 lines (40 loc) · 1.04 KB
/
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
/*
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
* */
void swap(int *p, int *q) {
int t = *p;
*p = *q;
*q = t;
}
void search(int *nums, int size, int ***arr, int *returnSize, int begin, int end) {
if (begin == end) {
(*returnSize)++;
*arr = (int **) realloc(*arr, sizeof(int *) * (*returnSize));
(*arr)[*returnSize - 1] = (int *) malloc(sizeof(int) * size);
for (int i = 0; i < size; i++)
(*arr)[*returnSize - 1][i] = nums[i];
return;
}
for (int i = begin; i <= end; i++) {
swap(nums + begin, nums + i); //try to use each element as the head;
search(nums, size, arr, returnSize, begin + 1, end);
swap(nums + begin, nums + i);
}
}
int **permute(int *nums, int size, int *returnSize) {
*returnSize = 0;
int **arr = (int **) malloc(sizeof(int *));
search(nums, size, &arr, returnSize, 0, size - 1);
return arr;
}