1. 程式人生 > 實用技巧 >讀《白帽子講Web安全》之安全意識篇(一)

讀《白帽子講Web安全》之安全意識篇(一)

題目描述

數字 n代表生成括號的對數,請你設計一個函式,用於能夠生成所有可能的並且 有效的 括號組合。

示例:

輸入:n = 3
輸出:[
       "((()))",
       "(()())",
       "(())()",
       "()(())",
       "()()()"
     ]

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/generate-parentheses

思路解析

生成\(n\)對括號的幾何\(S(n)\),有以下遞推關係:

\[S(n) = \sum_{i = 0}^n( LeftParentheses + S(n - i - 1) + RightParentheses + S(i)) \]

程式碼實現

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<vector<string>> dp;
        dp.push_back(vector<string>{ "" });
        for(int i = 1; i <= n; i++) {
            vector<string> cur_dp;
            for(int j = 0; j < i; j++) {
                for(string p : dp[j]) {
                    for(string q : dp[i - j - 1]) {
                        string str = "(" + p + ")" + q;
                        cur_dp.push_back(str);
                    }
                }
            }
            dp.push_back(cur_dp);
        }
        return dp[n];
    }
};