1. 程式人生 > 其它 >39. 組合總和 Combination Sum

39. 組合總和 Combination Sum

技術標籤:LeetCode

題目 <https://leetcode-cn.com/problems/combination-sum/>

日常回溯法

/**
 * Return an array of arrays of size *returnSize.
 * The sizes of the arrays are returned as *returnColumnSizes array.
 * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free().
 */

int **returnNums;
int *returnColSizes;
int returnLen;

void search(int* candidates, int candidatesSize,int target,int sum,int *tmp,int tmp_len,int index){
    if(sum > target){
        return;
    }

    if(sum == target){
        returnColSizes[returnLen] = tmp_len;
        returnNums[returnLen] = malloc(sizeof(int)*tmp_len);
        memcpy(returnNums[returnLen],tmp,sizeof(int)*tmp_len);
        returnLen++;
        return;
    }

    int i,j;
    for(i=index;i<candidatesSize;i++){
        tmp[tmp_len] = candidates[i];
        search(candidates,candidatesSize,target,sum + candidates[i],tmp,tmp_len+1,i);
    }
}

int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes){
    returnNums = malloc(sizeof(int**) * 10000);
    returnColSizes = malloc(sizeof(int*) * 10000);
    returnLen = 0;
    int *tmp = malloc(sizeof(int) * target);

    search(candidates,candidatesSize,target,0,tmp,0,0);

    free(tmp);
    *returnSize = returnLen;
    *returnColumnSizes = returnColSizes;
    return returnNums;
}