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:

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

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);
  }
}

posted on 2015-05-28 08:12  shini  阅读(82)  评论(0编辑  收藏  举报

导航