简单题。DFS。还是用Java写函数麻烦了。一开始把left<n的条件忘了。
import java.util.ArrayList;public class Solution { public ArrayListgenerateParenthesis(int n) { // Start typing your Java solution below // DO NOT write main() function ArrayList arr = new ArrayList (); ArrayList chars = new ArrayList (); dfs(arr, 0, 0, chars, n); return arr; } private void dfs(ArrayList arr, int left, int right, ArrayList chars, int n) { if (left + right + 1 == n * 2) { if (left < right) { // chars.add('(') - impossible // chars.remove(chars.size() - 1); } else { chars.add(')'); StringBuilder sb = new StringBuilder(); for (char c : chars) { sb.append(c); } arr.add(sb.toString()); chars.remove(chars.size() - 1); } } else { if (left > right) { chars.add(')'); dfs(arr, left, right + 1, chars, n); chars.remove(chars.size() - 1); } if (left < n) { chars.add('('); dfs(arr, left + 1, right, chars, n); chars.remove(chars.size() - 1); } } }}