題目描述
給定 n,表示有 n 對括號, 請寫一個函數以將其生成所有的括號組合,並返回組合結果。
點擊在線測評代碼
樣例 1:
輸入: 3
輸出: ["((()))", "(()())", "(())()", "()(())", "()()()"]
樣例 2:
輸入: 2
輸出: ["()()", "(())"]
題解
回溯. 逐個字符添加, 生成每一種組合.
一個狀態需要記錄的有: 當前字符串本身, 左括號數量, 右括號數量.
遞歸過程中解決:
- 如果當前右括號數量等於括號對數 n, 那麼當前字符串即是一種組合, 放入解中.
- 如果當前左括號數量等於括號對數 n, 那麼當前字符串後續填充滿右括號, 即是一種組合.
- 如果當前左括號數量未超過 n:
- 如果左括號多於右括號, 那麼此時可以添加一個左括號或右括號, 遞歸進入下一層
- 如果左括號不多於右括號, 那麼此時只能添加一個左括號, 遞歸進入下一層
比起自己刷題,有大神帶着刷肯定更好,專業的算法課程可以隨問隨答,在最短時間內提高算法水平,應對大廠面試。
/**
* This reference program is provided by @jiuzhang.com
* Copyright is reserved. Please indicate the source for forwarding
*/
public class Solution {
public ArrayList<String> generateParenthesis(int n) {
ArrayList<String> result = new ArrayList<String>();
if (n <= 0) {
return result;
}
helper(result, "", n, n);
return result;
}
public void helper(ArrayList<String> result,
String paren, // current paren
int left, // how many left paren we need to add
int right) { // how many right paren we need to add
if (left == 0 && right == 0) {
result.add(paren);
return;
}
if (left > 0) {
helper(result, paren + "(", left - 1, right);
}
if (right > 0 && left < right) {
helper(result, paren + ")", left, right - 1);
}
}
}
///////////////////// 九章硅谷求職算法集訓營版本
class Solution {
List<String> res = new ArrayList<>();
int n;
void gen(int nleft, int nright, String cur) {
if (nleft == n && nright == n) {
res.add(cur);
return;
}
if (nleft < n) {
gen(nleft + 1, nright, cur + "(");
}
if (nright < nleft) {
gen(nleft, nright + 1, cur + ")");
}
}
public List<String> generateParenthesis(int nn) {
n = nn;
gen(0, 0, "");
return res;
}
}