标签:
原题链接在这里:https://leetcode.com/problems/generate-parentheses/
采用递归调用helper, left, right, 代表还需要加几个左括号和几个右括号。起始赋值都为n, e.g. 若n=3, 就说明一共需要加三个左括号和三个右括号。
递归函数helper终止条件有两个,一个left>right, 说明")"已经比"("加多了,不合法,另一个终止条件是left==0 && right==0说明都加完了。
否则先加左括号,再加右括号。
与Unique Binary Search Trees II类似。
AC Java:
public class Solution { public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<String>(); if(n <= 0){ return res; } String str = new String(); helper(n, n, str, res); return res; } private void helper(int left, int right, String str, List<String> res){ if(left > right){ //if left > right, it means remaining "(" is more than remaining ")" //This means already added more ")" than "(", which is illegal. return; } if(left == 0 && right == 0){ res.add(str); return; } if(left > 0){ helper(left-1, right, str+"(", res); } if(right > 0){ helper(left, right-1, str+")", res); } } }
标签:
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/4825126.html