LeetCode 40. 组合总和 II Combination Sum II(C语言)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hang404/article/details/85164941

题目描述:

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
[1,2,2],
[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 + 1);
        while(i + 1 < n && nums[i] == nums[i + 1])
            i++;
    }
}
int comp(const void* a, const void* b) {
    return *(int*)a - *(int*)b;
}
int** combinationSum2(int* candidates, int candidatesSize, int target, int** columnSizes, int* returnSize) {
    int** result = NULL;
    qsort(candidates, candidatesSize, sizeof(int), comp);
    int* before = (int*)malloc(100 * sizeof(int));
    combine(&result, returnSize, candidates, candidatesSize, target, columnSizes, before, 0, 0, 0);
    free(before);
    return result;
}

猜你喜欢

转载自blog.csdn.net/hang404/article/details/85164941