[Leetcode-22]Generate Parentheses 生成圆括号

来源:互联网 发布:女朋友漂亮知乎 编辑:程序博客网 时间:2024/05/17 07:30

0. 题目概要

  • 题目概要
  • 分析
  • AC代码
  • Java AC代码

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个左右括号的括号序列。


1. 分析

这里写图片描述


2. AC代码

DFS方法记录了:

  • 左括号个数
  • 当前的”部分解”

这里写图片描述

class Solution {public:    void help(int n, int x, int y, string now, vector<string> &answer){        if(y == n){            answer.push_back(now);            return;        }        if(x < n){            help(n, x+1, y, now + "(", answer);        }        if(x > y){            help(n, x, y+1, now + ")", answer);        }    }    vector<string> generateParenthesis(int n) {        vector<string> answer;        help(n, 0, 0, "", answer);        return answer;    }};

3. Java AC代码

Java回溯法:

 public List<String> generateParenthesis(int n) {        List<String> list = new ArrayList<String>();        backtrack(list, "", 0, 0, n);        return list;    }    public void backtrack(List<String> list, String str, int open, int close, int max){        if(str.length() == max*2){            list.add(str);            return;        }        if(open < max)            backtrack(list, str+"(", open+1, close, max);        if(close < open)            backtrack(list, str+")", open, close+1, max);    }

The idea here is to only add ‘(’ and ‘)’ that we know will guarantee us a solution (instead of adding 1 too many close). Once we add a ‘(’ we will then discard it and try a ‘)’ which can only close a valid ‘(‘. Each of these steps are recursively called.

原创粉丝点击