• 22. Generate Parentheses


    问题:

    给定一个计量括号数量的数字n,求所有的括号组合可能序列。

    Example 1:
    Input: n = 3
    Output: ["((()))","(()())","(())()","()(())","()()()"]
    
    Example 2:
    Input: n = 1
    Output: ["()"]
     
    Constraints:
    1 <= n <= 8
    

      

    解法:Backtracking(回溯算法)

    参数:

    • path:到目前为止构成的括号序列。
    • optionlists:当前所剩下的左括号数量。(本次是否还能选择左括号)

    处理:

    • 退出条件:if(optionlists的剩下左括号数量==0) 则将剩下的右括号追加到path,将path加入res,return
    • for所有可选项:追加左括号or追加右括号(若右括号剩余<=左括号,不满足括号性质:先'(',后')'必须成对出现)
      • 做选择:path+='(' or path+=')'
      • 递归:
        • 选左括号时:backtracking(path, optionlists-1<左括号数量-1>, optend<右括号数量不变>) or
        • 选右括号时:backtracking(path, optionlists<左括号数量不变>, optend-1<右括号数量-1>) 
      • 撤销选择:path.pop_back()

    代码参考:

     1 class Solution {
     2 public:
     3     vector<string> generateParenthesis(int n) {
     4         vector<string> res;
     5         backtracking(res, "", n, n);
     6         return res;
     7     }
     8     void backtracking(vector<string>& res, string path, int optionlist, int optend) {
     9         if(optionlist == 0) {
    10             while(optend){
    11                 path+=')';
    12                 optend--;
    13             }
    14             res.push_back(path);
    15             return;
    16         }
    17         backtracking(res, path+'(', optionlist-1, optend);
    18         if(optend <= optionlist) return;//'(' must before ')'
    19         backtracking(res, path+')', optionlist, optend-1);
    20         return;
    21     }
    22 };
  • 相关阅读:
    .NET之权限管理
    .NET之带星期的日期显示
    ASP.net MVC 同一view或页面使用多个Model或数据集的方法
    ISBN号校检程序(C#与SQL版)
    ASP操作类似多维Cookies
    C# webBrowser自动登陆windows集成验证方法
    JOI 系列乱做
    NOI2021 部分题解
    「NEERC 2015」Jump 题解
    CF/AT 乱做
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14222511.html
Copyright © 2020-2023  润新知