简单题。DFS。还是用Java写函数麻烦了。一开始把left<n的条件忘了。
import java.util.ArrayList; public class Solution { public ArrayList<String> generateParenthesis(int n) { // Start typing your Java solution below // DO NOT write main() function ArrayList<String> arr = new ArrayList<String>(); ArrayList<Character> chars = new ArrayList<Character>(); dfs(arr, 0, 0, chars, n); return arr; } private void dfs(ArrayList<String> arr, int left, int right, ArrayList<Character> 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); } } } }
Python3
class Solution: def generateParenthesis(self, n: int) -> List[str]: output = [] def backtrack(s: str, leftCnt: int, rightCnt: int, n: int): if n == leftCnt and n == rightCnt: output.append(s) else: if leftCnt < n: backtrack(s + '(', leftCnt + 1, rightCnt, n) if rightCnt < leftCnt: backtrack(s + ')', leftCnt, rightCnt + 1, n) if n > 0: backtrack('', 0, 0, n) return output