LeetCode - Algorithms
  • Introduction
  • 1. Two Sum
  • 2. Add Two Numbers
  • 3. Longest Substring Without Repeating Characters
  • 4. Median of Two Sorted Arrays
  • 5. Longest Palindromic Substring
  • 6. ZigZag Conversion
  • 7. Reverse Integer
  • 8. String to Integer (atoi)
  • 9. Palindrome Number
  • 10. Regular Expression Matching
  • 11. Container with Most Water
  • 12. Integer to Roman
  • 13. Roman to Integer
  • 14. Longest Common Prefix
  • 15. 3Sum
  • 16. 3Sum Closest
  • 17. Letter Combinations of a Phone Number
  • 18. 4Sum
  • 19. Remove Nth Node From End of List
  • 20. Valid Parentheses
  • 21. Merge Two Sorted Lists
  • 22. Generate Parentheses
  • 23. Merge k Sorted Lists
  • 24. Swap Nodes in Pairs
  • 25. Reverse Nodes in k-Group
  • 26. Remove Duplicates from Sorted Array
  • 27. Remove Element
  • 28. Implement strStr()
  • 29. Divide Two Integers
  • 30. Substring with Concatenation of All Words
  • 31. Next Permutation
  • 32. Longest Valid Parentheses
  • 33. Search in Rotated Sorted Array
  • 34. Search for a Range
  • 35. Search Insert Position
  • 36. Valid Sudoku
  • 37. Sudoku Solver
  • 38. Count and Say
  • 39. Combination Sum
Powered by GitBook
On this page
  • Problem
  • Analysis
  • Code

22. Generate Parentheses

Problem

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Related Topics:

String Backtracking

Analysis

方法一:递归。

方法二:非递归。

f(0): ""
f(1): "("f(0)")"
f(2): "("f(0)")"f(1) , "("f(1)")"
f(3): "("f(0)")"f(2) , "("f(1)")"f(1) , "("f(2)")"
f(n): "("f(0)")"f(n-1) , "("f(1)")"f(n-2) , "("f(2)")"f(n-3) ... "("f(n-1)")"

Code

递归

class Solution {

    private lateinit var list: MutableList<String>

    fun generateParenthesis(n: Int): List<String> {

        list = mutableListOf()
        generateParenthesis(n, 0, "")

        return list
    }

    private fun generateParenthesis(n: Int, stack: Int, s: String) {

        when {
            n < 0 || stack < 0 -> return
            n == 0 && stack == 0 -> list.add(s)
            else -> {
                generateParenthesis(n - 1, stack + 1, s + "(")
                generateParenthesis(n, stack - 1, s + ")")
            }
        }
    }
}

非递归

class Solution {

    fun generateParenthesis(n: Int): List<String> {

        val list = mutableListOf<List<String>>()
        list.add(listOf(""))

        var temp: MutableList<String>
        for (i in 1..n) {

            temp = mutableListOf()
            for (j in 0 until i) {
                for (first in list[j]) {
                    list[i - 1 - j].mapTo(temp) { "($first)$it" }
                }
            }
            list.add(temp)
        }

        return list[n]
    }
}
Previous21. Merge Two Sorted ListsNext23. Merge k Sorted Lists

Last updated 6 years ago