22. Generate Parentheses

来源:互联网 发布:淘宝店铺首页全屏大图 编辑:程序博客网 时间:2024/06/10 11:22

Generate Parenthese生成圆括号

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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
难点关键在与怎么样生成所有的组合?本题使用了两个if 通过递归依次来输出所有的可能性

代码

public class Solution {    public List<String> generateParenthesis(int n) {      List<String> list = new ArrayList<String>();        backtrack(list, "", 0, 0, n);        return list;    }    public void backtrack(List<String> list, String str, int open, int close, int max){  //声明一个函数来进行计算open-‘(’   close-‘)’        if(str.length() == max*2){  //每一组括号            list.add(str);            return;        }        if(open < max)            backtrack(list, str+"(", open+1, close, max);        if(close < open)  //注意不是max,因为需要保证最后一个括号是)            backtrack(list, str+")", open, close+1, max);    }  }
0 0
原创粉丝点击