Skip to content

Commit 1c1e2f0

Browse files
C: add problem 46 and test function
1 parent 824dd0e commit 1c1e2f0

File tree

1 file changed

+38
-23
lines changed

1 file changed

+38
-23
lines changed

C/1-50/46-Permutations.c

Lines changed: 38 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -15,37 +15,52 @@
1515
*/
1616
#include
1717
#include
18-
int** permute(int* nums, int numsSize, int* returnSize) {
18+
19+
void backtrack(int **result, int *rowIndex, int *row, int colIndex, int *nums, int numsSize) {
20+
if (colIndex == numsSize) {
21+
int *r = malloc(sizeof(int) * numsSize);
22+
for (int i = 0; i < numsSize; ++i) {
23+
r[i] = row[i];
24+
}
25+
26+
result[(*rowIndex)++] = r;
27+
return;
28+
}
29+
for (int i = 0; i < numsSize; ++i) {
30+
int j;
31+
for (j = 0; j < colIndex; ++j) {
32+
if (nums[i] == row[j])
33+
break;
34+
}
35+
if (j != colIndex)
36+
continue;
37+
row[colIndex] = nums[i];
38+
backtrack(result, rowIndex, row, colIndex + 1, nums, numsSize);
39+
}
40+
}
41+
42+
int **permute(int *nums, int numsSize, int *returnSize) {
1943
*returnSize = 0;
20-
if(numsSize == 0)
44+
if (numsSize == 0)
2145
return NULL;
22-
*returnSize = 1;
23-
24-
for(int i = 1; i <=numsSize;i++)
46+
47+
for (int i = 1; i <= numsSize; i++)
2548
*returnSize *= i;
49+
int **result = malloc(sizeof(int *) * (*returnSize)), *row = malloc(sizeof(int) * numsSize);
2650

27-
int ** result = malloc(sizeof(int*)**returnSize);
28-
for(int i = 0;i < *returnSize;i++)
29-
result[i] = malloc(sizeof(int)*numsSize);
30-
int start = 0,index = start,cur=*returnSize;
31-
for(int i = 0; i <numsSize;i++){
32-
index = start-1;
33-
cur/=numsSize;
34-
for(int j =0; j<*returnSize;j++){
35-
result[j][i] = nums[++index%numsSize];
36-
}
37-
start++;
38-
}
51+
*returnSize = 0;
52+
backtrack(result, returnSize, row, 0, nums, numsSize);
53+
free(row);
3954

4055
return result;
4156
}
4257

43-
void testPermute(){
44-
int a[] = {1,2,3},count = 0;
45-
int** result = permute(a,3,&count);
46-
for(int i = 0; i <count;i++){
47-
for(int j =0 ;j<3;j++){
48-
printf("%d,",result[i][j]);
58+
void testPermute() {
59+
int a[] = {1, 2, 3, 4}, count = 1, size = 0;
60+
int **result = permute(a, count, &size);
61+
for (int i = 0; i < size; i++) {
62+
for (int j = 0; j < count; j++) {
63+
printf("%d,", result[i][j]);
4964
}
5065
printf("\n");
5166
}

0 commit comments

Comments
 (0)