|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <stdbool.h> |
| 4 | +#include <string.h> |
| 5 | + |
| 6 | +static void dfs(int *nums, int size, int start, int target, int num, |
| 7 | + int *solution, int len, int **results, int *column_sizes, int *count) |
| 8 | +{ |
| 9 | + int i; |
| 10 | + if (len == num) { |
| 11 | + if (target == 0) { |
| 12 | + results[*count] = malloc(len * sizeof(int)); |
| 13 | + memcpy(results[*count], solution, len * sizeof(int)); |
| 14 | + column_sizes[*count] = len; |
| 15 | + (*count)++; |
| 16 | + } |
| 17 | + } else if (target > 0) { |
| 18 | + for (i = start; i < size; i++) { |
| 19 | + solution[len] = nums[i]; |
| 20 | + dfs(nums, size, i + 1, target - nums[i], num, solution, len + 1, results, column_sizes, count); |
| 21 | + } |
| 22 | + } |
| 23 | +} |
| 24 | + |
| 25 | +/** |
| 26 | + ** Return an array of arrays of size *returnSize. |
| 27 | + ** The sizes of the arrays are returned as *columnSizes array. |
| 28 | + ** Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). |
| 29 | + **/ |
| 30 | +static int** combinationSum3(int k, int n, int** columnSizes, int* returnSize) |
| 31 | +{ |
| 32 | + int i, count = 9; |
| 33 | + int *nums = malloc(count * sizeof(int)); |
| 34 | + for (i = 0; i < count; i++) { |
| 35 | + nums[i] = i + 1; |
| 36 | + } |
| 37 | + |
| 38 | + int *solution = malloc(k * sizeof(int)); |
| 39 | + int **results = malloc(100 * sizeof(int *)); |
| 40 | + *columnSizes = malloc(100 * sizeof(int)); |
| 41 | + *returnSize = 0; |
| 42 | + dfs(nums, count, 0, n, k, solution, 0, results, *columnSizes, returnSize); |
| 43 | + return results; |
| 44 | +} |
| 45 | + |
| 46 | +int main(int argc, char **argv) |
| 47 | +{ |
| 48 | + if (argc != 3) { |
| 49 | + fprintf(stderr, "Usage: ./test k n\n"); |
| 50 | + exit(-1); |
| 51 | + } |
| 52 | + |
| 53 | + int i, j; |
| 54 | + int k = atoi(argv[1]); |
| 55 | + int n = atoi(argv[2]); |
| 56 | + int *sizes, count = 0; |
| 57 | + int **lists = combinationSum3(k, n, &sizes, &count); |
| 58 | + for (i = 0; i < count; i++) { |
| 59 | + for (j = 0; j < sizes[i]; j++) { |
| 60 | + printf("%d ", lists[i][j]); |
| 61 | + } |
| 62 | + printf("\n"); |
| 63 | + } |
| 64 | + return 0; |
| 65 | +} |
0 commit comments