|
15 | 15 | */
|
16 | 16 | #include
|
17 | 17 | #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) { |
19 | 43 | *returnSize = 0;
|
20 |
| - if(numsSize == 0) |
| 44 | + if (numsSize == 0) |
21 | 45 | return NULL;
|
22 |
| - *returnSize = 1; |
23 |
| - |
24 |
| - for(int i = 1; i <=numsSize;i++) |
| 46 | + |
| 47 | + for (int i = 1; i <= numsSize; i++) |
25 | 48 | *returnSize *= i;
|
| 49 | + int **result = malloc(sizeof(int *) * (*returnSize)), *row = malloc(sizeof(int) * numsSize); |
26 | 50 |
|
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); |
39 | 54 |
|
40 | 55 | return result;
|
41 | 56 | }
|
42 | 57 |
|
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]); |
49 | 64 | }
|
50 | 65 | printf("\n");
|
51 | 66 | }
|
|
0 commit comments