Skip to content
New issue

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

22. Generate Parentheses #22

Open
yunshuipiao opened this issue Jun 5, 2019 · 0 comments
Open

22. Generate Parentheses #22

yunshuipiao opened this issue Jun 5, 2019 · 0 comments
Labels
backtrack backtrack

Comments

@yunshuipiao
Copy link
Owner

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:

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

解法

回溯法,可以解决背包,排列等相关问题

直接看代码分析,插入打印代码方便理解

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))
    }
}
@yunshuipiao yunshuipiao added the backtrack backtrack label Jun 5, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backtrack backtrack
Projects
None yet
Development

No branches or pull requests

1 participant