22. Generate Parentheses (backTracking)

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

"((()))", "(()())", "(())()", "()(())", "()()()"

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** generateParenthesis(int n, int* returnSize) {
    char** returnArray = NULL;
    if(n==0) return returnArray;
    
    char* elem = malloc(sizeof(char)*(n*2+1));
    returnArray = malloc(sizeof(char*)*2000);
    
    backTracking(n,0,elem, 0, returnArray, returnSize);
    return returnArray;
}

/*
 *@parameter
 *left(in): number of left parenthesis to add
 *right(in): number of right parenthesis to add
*/
void backTracking(int left, int right, char* elem, int pElem, char** returnArray, int* returnSize ){
    int i, j, pTmp;
    //逐一填(,然后逐一填),每次都要回溯
    for(i = 1; i < left; i++){ //fill (
        elem[pElem] = '(';
        pElem++;
        pTmp = pElem;
        for(j = 1; j <= i+right; j++){ //fill )
            elem[pTmp] = ')';
            pTmp++;
            backTracking(left-i,i+right-j,elem, pTmp, returnArray, returnSize);
        }
    }
    
    //最后,是只填了(的情况,那么一次性填写所有的)
    elem[pElem] = '(';
    pElem++;
    for(i = 1; i <= right+left; i++){
        elem[pElem] = ')';
        pElem++;
    }
    elem[pElem] = '\0';
    char* returnElem = malloc(sizeof(char) * (pElem+1));
    memcpy(returnElem, elem, sizeof(char) * (pElem+1));
    returnArray[*returnSize] = returnElem;
    (*returnSize)++;
}

 

posted on 2016-04-24 06:51  joannae  阅读(251)  评论(0编辑  收藏  举报

导航