22 Generate Parentheses

定義問題:左括號,右括號需要匹配,也就是必須相等

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

n = 3 ,說明需要3個左括號,3個右括號

left : 沒有匹配的“(”
right:
dfs(int left, int right, char* str, char*result, int returnSize, int n)

left-1: 添加"("
right-1: 添加")"

二叉遞歸:[30,12,20,03,11,11,#,#,02,02,10,02,10]

recursion()
{
     
    if (end_condition)
{

              solve;     
     
    }
else
{     
        //在將問題轉換為子問題描述的每一步,都解決該步中剩余部分的問題。
          
        if()
            recursion();
        if()
            recursion();
    }

}
#define SIZE 10000

void dfs(int left, int right, char* str, char**result, int* returnSize, int n) {
    if((left == 0) && (right == 0))
        result[(*returnSize)++] = str;
    else {
        char* newStr = (char *)malloc(sizeof(char) * (2*n+1));
        if(left > 0) {
            strcpy(newStr, str);
            dfs(left-1, right+1, strcat(newStr, "("), result, returnSize, n);
        }
        if(right > 0) {
            strcpy(newStr, str);
            dfs(left, right-1, strcat(newStr, ")"), result, returnSize, n);
        }
    }
}

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** generateParenthesis(int n, int* returnSize) {
    char** result = (char **)malloc(sizeof(char *) * SIZE);
    dfs(n, 0, "", result, returnSize, n);
    return result;
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容