题目链接

思路

主要是使用递归方法,对于一个字符串,记录一下其左右括号的数量,若数量正好,加入集合。主要是根据左右括号的数量来判断下次应该加入什么括号

代码

  1. class Solution {
  2. private fun generate(left: Int, right: Int, n: Int, result: MutableSet<String>, arr: CharArray, c: Char) {
  3. arr[left + right - 1] = c
  4. if (right == n){
  5. result.add(String(arr))
  6. return
  7. }
  8. if (left > right) {
  9. if (left < n) {
  10. generate(left + 1, right, n, result, arr, '(')
  11. generate(left, right + 1, n, result, arr, ')')
  12. }else {
  13. generate(left, right + 1, n, result, arr, ')')
  14. }
  15. }else if (left == right) {
  16. generate(left + 1, right, n, result, arr, '(')
  17. }
  18. }
  19. fun generateParenthesis(n: Int): List<String> {
  20. val result = mutableSetOf<String>()
  21. val arr = CharArray(2 * n)
  22. generate(1, 0, n, result, arr,'(')
  23. return result.toList()
  24. }
  25. }