【LeetCode】Generate Parentheses (2 solutions)

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:

"((()))", "(()())", "(())()", "()(())", "()()()"

解法一:递归

借助栈,‘(‘、‘)‘构成一对分别进出栈。最后栈为空,则输入括号构成的字符串是合法的。

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        if(n == 0)
            return result;
        //first must be ‘(‘
        string cur = "(";
        stack<char> s;
        s.push(‘(‘);

        Helper(result, cur, s, 2*n-1);
        return result;
    }
    void Helper(vector<string>& result, string cur, stack<char> s, int num)
    {
        if(num == 1)
        {//must be ‘)‘
            if(s.top() == ‘(‘ && s.size() == 1)
            {//all matched
                cur += ‘)‘;
                result.push_back(cur);
            }
        }
        else
        {
            //‘(‘ always push
            string str1 = cur;
            str1 += ‘(‘;
            s.push(‘(‘);
            Helper(result, str1, s, num-1);
            s.pop();

            //‘)‘
            if(!s.empty())
            {//prune. never begin with ‘)‘
                string str2 = cur;
                str2 += ‘)‘;
                if(s.top() == ‘(‘)
                    s.pop();    //check empty() before access top()
                else
                    s.push(‘)‘);
                Helper(result, str2, s, num-1);
            }
        }
    }
};

解法二:递归

稍作分析可知,栈是不必要的,只要记录字符串中有几个‘(‘,记为count。

每进入一个‘(‘, count ++. 每匹配一对括号, count--。

最终全部匹配,需要count==0

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        if(n == 0)
            return result;
        //first must be ‘(‘
        string cur = "(";
        int count = 1;  //number of (‘s in cur

        Helper(result, cur, count, 2*n-1);
        return result;
    }
    void Helper(vector<string>& result, string cur, int count, int num)
    {
        if(num == 1)
        {//must be ‘)‘
            if(count == 1)
            {//all matched
                cur += ‘)‘;
                result.push_back(cur);
            }
        }
        else
        {
            //‘(‘ always push
            string str1 = cur;
            str1 += ‘(‘;
            count ++;
            Helper(result, str1, count, num-1);
            count --;

            //‘)‘
            if(count != 0)
            {//prune. never begin with ‘)‘
                string str2 = cur;
                str2 += ‘)‘;
                count --;
                Helper(result, str2, count, num-1);
            }
        }
    }
};

时间: 2024-10-20 01:32:16

【LeetCode】Generate Parentheses (2 solutions)的相关文章

【leetcode】Generate Parentheses

题目: 给定整数n,返回n对匹配的小括号字符串数组. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 分析: 这种问题的模式是:1)问题的解有多个 ,2)每个解都是由多个有效的 "步骤" 组成的,3)变更以有解的某个或某些"步骤"

【LeetCode】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: "((()))", "(()())", "(())()", "()(())", "()()()" [思

【Leetcode】Generate Parentheses in JAVA

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思想做

【leetcode】 Generate Parentheses (middle)☆

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: "((()))", "(()())", "(())()", "()(())", "()()()" 思路:产生所有

【LeetCode】Single Number (2 solutions)

Single Number Given an array of integers, every element appears twice except for one. Find that single one. Note:Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory? 解法一:用map记录每个元素的次数,返回次数为1的元素 cl

【LeetCode】Reverse Integer (2 solutions)

Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 click to show spoilers. Have you thought about this? Here are some good questions to ask before coding. Bonus points for you if you have alread

【leetcode】Valid Parentheses

Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]"

【LeetCode】Same Tree (2 solutions)

Same Tree Given two binary trees, write a function to check if they are equal or not. Two binary trees are considered equal if they are structurally identical and the nodes have the same value. 解法一:递归 /** * Definition for binary tree * struct TreeNod

【LeetCode】Plus One (2 solutions)

Plus One Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list. 从个位数字往前扫,只要一个数字不为9,即可加1返回. 如果直到最高位仍为9,则说明结果为100…0 解法一: 可能会使用额外空间与复制