码迷,mamicode.com
首页 > 其他好文 > 详细

22. Generate Parentheses

时间:2015-05-28 09:24:31      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

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:

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

Cracking Interview 原题,递归回溯即可,只需注意右括号少于左括号。

public class Solution {
  public List<String> generateParenthesis(int n) {
  List<String> result = new ArrayList<>();
    helper(n, 0, 0, "", result);
    return result;
  }

  public void helper(int n, int left, int right, String cur, List<String> result) {
    if (left < right) {
      return;
    }
    if (left == right && n == right) {
      result.add(cur);
      return;
    }
    if (left <= n) {
      helper(n, left + 1, right, cur + "(", result);
    }
    helper(n, left, right + 1, cur + ")", result);
  }
}

22. Generate Parentheses

标签:

原文地址:http://www.cnblogs.com/shini/p/4534954.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!