Leetcode||22.Generate Parentheses

来源:互联网 发布:新开淘宝店物流 编辑:程序博客网 时间:2024/06/05 16:44

22. Generate Parentheses

  • Total Accepted: 116853
  • Total Submissions: 284854
  • Difficulty: Medium
  • Contributors: Admin

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:

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

讲道理,这题我还是看人家的做法做的,不是很会做,思想居然是深搜。

代码如下:

public class Solution {    public List<String> generateParenthesis(int n) {        List<String> res = new ArrayList<String>();        String item = new String();        if (n<=0) {return res;}        dfs(res,item,n,n);        return res;    }private void dfs(List<String> res, String item, int left, int right) {if (left > right) {return;}if (left==0&&right==0) {res.add(new String(item));return;}if (left>0) {dfs(res, item+'(', left-1, right);}if (right>0) {dfs(res, item+')', left, right-1);}}}


0 0