[leetcode] 22.Generate Parentheses

来源:互联网 发布:大数据金融的特点 编辑:程序博客网 时间:2024/05/01 02:31

题目:
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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
题意:
给n对括号,写一个方程去给出所有合法的括号搭配。合法的括号搭配的意思是当右括号出现时,前面必然有与之匹配的左括号。
思路:
这道题目考察的是使用回溯的方法递归求解题目。我们知道n是括号的对数,那么最终的字符串中有2*n个符号,其中n个是’(‘, n个是’)’。所以我们对这2*n个位置进行扫描,查看能存放的符号的所有组合。

1.当所有的’(‘都出现了后,那么接下来的可能就只有剩余的’)’都加到当前字符串的后面这种可能。

  1. 当前位置存放下’(‘,继续扫描下一个位置。
  2. 如果前面位置的’(‘数大于’)’数,那么这个位置是可以放入’)’。
    所以我们在代码中不光要保存当前扫描到的字符串的符号组成,还要保存’(‘与’)’的数目。
    以上。
    代码如下:
class Solution {public:    vector<string> generateParenthesis(int n) {        vector<string> result;        if(n == 0)return result;        string temp = "";        getAllParenthesis(result, temp, n, 0, 0);        return result;    }    void getAllParenthesis(vector<string>& result, string temp, int &n, int l, int r) {        if(l == n) {            string s(n - r, ')');            temp += s;            result.push_back(temp);            return;        }        temp.push_back('(');        getAllParenthesis(result, temp, n, l + 1, r);        temp.pop_back();        if( r < l) {                temp.push_back(')');                getAllParenthesis(result, temp, n, l, r + 1);                temp.pop_back();        }    }};
0 0
原创粉丝点击