• 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] = '';
        char* returnElem = malloc(sizeof(char) * (pElem+1));
        memcpy(returnElem, elem, sizeof(char) * (pElem+1));
        returnArray[*returnSize] = returnElem;
        (*returnSize)++;
    }
  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/5426273.html
Copyright © 2020-2023  润新知