[Algo] 66. All Valid Permutations Of Parentheses I

Given N pairs of parentheses “()”, return a list with all the valid permutations.

Assumptions

  • N > 0

Examples

  • N = 1, all valid permutations are ["()"]
  • N = 3, all valid permutations are ["((()))", "(()())", "(())()", "()(())", "()()()"]
public class Solution {
  public List<String> validParentheses(int n) {
    // Write your solution here
    List<String> res = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    helper(res, n, n, sb);
    return res;
  }

  private void helper(List<String> res, int left, int right, StringBuilder sb) {
    if (left == 0 && right == 0) {
      res.add(sb.toString());
      return;
    }
    if (left > 0) {
      sb.append("(");
      helper(res, left - 1, right, sb);
      sb.deleteCharAt(sb.length() - 1);
    }
    if (right > left) {
      sb.append(")");
      helper(res, left, right - 1, sb);
      sb.deleteCharAt(sb.length() - 1);
    }
  }
}
原文地址:https://www.cnblogs.com/xuanlu/p/12316007.html