1. 程式人生 > >LeetCode 39. 組合總和 Combination Sum(C語言)

LeetCode 39. 組合總和 Combination Sum(C語言)

題目描述:

給定一個無重複元素的陣列 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target 的組合。
candidates 中的數字可以無限制重複被選取。

說明:

  • 所有數字(包括 target)都是正整數。
  • 解集不能包含重複的組合。

示例 1:

輸入: candidates = [2,3,6,7], target = 7,
所求解集為:
[
[7],
[2,2,3]
]

示例 2:

輸入: candidates = [2,3,5], target = 8,
所求解集為:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

題目解答:

方法1:回溯

迴圈加遞迴。儲存前邊數字的和,並向下遞迴嘗試。
執行時間4ms,程式碼如下。

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *columnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */
void combine(int***
result, int* size, int* nums, int n, int target, int** column, int* before, int bef, int sum, int start) { if(sum == target) { (*size)++; result[0] = (int**)realloc(result[0], *size * sizeof(int*)); result[0][*size - 1] = (int*)malloc(bef * sizeof(int)); column[0] = (
int*)realloc(column[0], *size * sizeof(int)); column[0][*size - 1] = bef; memcpy(result[0][*size - 1], before, sizeof(int) * bef); return ; } int i = 0; for(i = start; i < n; i++) { if(sum + nums[i] > target) continue; before[bef] = nums[i]; combine(result, size, nums, n, target, column, before, bef + 1, sum + nums[i], i); } } int** combinationSum(int* candidates, int candidatesSize, int target, int** columnSizes, int* returnSize) { int** result = NULL; int* before = (int*)malloc(100 * sizeof(int)); combine(&result, returnSize, candidates, candidatesSize, target, columnSizes, before, 0, 0, 0); free(before); return result; }