[leetcode]22. Generate Parentheses
阿新 • • 發佈:2018-12-01
Solution 1: 遞歸回溯法
回溯就是找到所有的解,一直沒用java寫過回溯,突然有點懵逼
一直往左下走
if (open < max)
backtrack(ans, cur+"(", open+1, close, max);
cur還是左下之前的值,再繼續往右下走
if (close < open)
backtrack(ans, cur+")", open, close+1, max);
這個類似與0-1揹包問題,時間複雜度是0(2的h(n)次方),其中h(n)是一條路徑的長度,在這一題就是2n。所以時間複雜度是2的2
class Solution { public List<String> generateParenthesis(int n) { List<String> ans = new ArrayList(); backtrack(ans, "", 0, 0, n); return ans; } public void backtrack(List<String> ans, String cur, int open, int close, int max){ if (cur.length() == max * 2) { ans.add(cur); return; } if (open < max) backtrack(ans, cur+"(", open+1, close, max); if (close < open) backtrack(ans, cur+")", open, close+1, max); } }
Solution 2: 巧妙的遞迴
其中left和right都是有效的string
class Solution { public List<String> generateParenthesis(int n) { List<String> ans = new ArrayList(); if (n == 0) { ans.add(""); } else { for (int c = 0; c < n; ++c) for (String left: generateParenthesis(c)) for (String right: generateParenthesis(n-1-c)) ans.add("(" + left + ")" + right); } return ans; } }