We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
回溯法,可以解决背包,排列等相关问题
直接看代码分析,插入打印代码方便理解
import org.testng.annotations.Test fun generateParenthesis(n: Int): List<String> { val result = arrayListOf<String>() backtracking(result, "", 0, 0, n) return result.toList() } fun backtracking(result: ArrayList<String>, s: String, open: Int, close: Int, max: Int) { println(s) if (s.length == 2 * max) { result.add(s) println("----") return } if (open < max) { backtracking(result, "$s(", open + 1, close, max) } if (close < open) { backtracking(result, "$s)", open ,close + 1, max) } } @Test fun _0022() { arrayListOf(3).forEach { println(generateParenthesis(it)) } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
22. Generate Parentheses
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:
解法
回溯法,可以解决背包,排列等相关问题
直接看代码分析,插入打印代码方便理解
The text was updated successfully, but these errors were encountered: