22. Generate Parentheses

来源:互联网 发布:kudo编程 编辑:程序博客网 时间:2024/06/06 09:16

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:

    [  "((()))",  "(()())",  "(())()",  "()(())",  "()()()"]
  • 题目大意:给定一个整数n,写一个函数,返回所有括号组合

  • 思路:回溯法,首先添加左括号,之后添加又括号,又括号的个数不能超过左括号。

  • 代码

    package String;import java.util.ArrayList;import java.util.List;/*** @Author OovEver* @Date 2017/12/10 20:59*/public class LeetCode22 {  public List<String> generateParenthesis(int n) {      List<String> result = new ArrayList<>();      backtrack(result, "", 0, 0, n);      return result;  }//open与close分别为左右括号个数  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);      }  }  public static void main(String[] args) {      LeetCode22 test = new LeetCode22();      System.out.println(test.generateParenthesis(3));  }}
原创粉丝点击