题解 | #括号生成#
括号生成
https://www.nowcoder.com/practice/c9addb265cdf4cdd92c092c655d164ca
import java.util.*; public class Solution { private ArrayList<String> res = new ArrayList<>(); /** * * @param n int整型 * @return string字符串ArrayList */ public ArrayList<String> generateParenthesis (int n) { // write code here if (n < 1) { return res; } backtrack(new LinkedList<>(), n, n); return res; } private void backtrack(LinkedList<Character> list, int left, int right) { if (left > right || left < 0 || right < 0) { return; } if (left == 0 && right == 0) { res.add(list2Str(list)); return; } list.add('('); backtrack(list, left - 1, right); list.removeLast(); list.add(')'); backtrack(list, left, right - 1); list.removeLast(); } private String list2Str(LinkedList<Character> list) { StringBuilder sb = new StringBuilder(); for (char ch : list) { sb.append(ch); } return sb.toString(); } }