zoukankan      html  css  js  c++  java
  • LeetCode 22. Generate Parentheses

    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:

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

    简单搜索,用dfs列出所有情况就行了

    class Solution {
        
        void dfs(vector<string> &vec, string str, int x, int y)
        {
            if(x == 0 && y == 0)
            {
                vec.push_back(str);
                return ;
            }
            
            if(x == y)
                dfs(vec, str+'(', x-1, y);
            else
            {
                if(x > 0)
                    dfs(vec, str+'(', x-1, y);
                dfs(vec, str+')', x, y-1);
            }
        }
        
    public:
        vector<string> generateParenthesis(int n) {
            string str;
            vector<string>vec;
            int x = n, y = n;
            dfs(vec, str, x,  y);
            return vec;
        }
    };
    
  • 相关阅读:
    [leetCode]剑指 Offer 43. 1~n整数中1出现的次数
    [leetCode]剑指 Offer 42. 连续子数组的最大和
    HDU
    HDU
    HDU
    HDU
    HDU
    HDU
    POJ
    POJ
  • 原文地址:https://www.cnblogs.com/aiterator/p/6592081.html
Copyright © 2011-2022 走看看