采用递归树的思想实现java code

欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入

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:

“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

java code : 采用递归树的思想,当左括号数大于右括号数时可以加左或者右括号,否则只能加左括号,当左括号数达到n时,剩下全部加右括号。

public class Solution {

public ArrayList<String> generateParenthesis(int n) {

// Note: The Solution object is instantiated only once and is reused by each test case.

ArrayList<String> res = new ArrayList<String>();

generate(res, “”, 0, 0, n);

return res;

}

public void generate(ArrayList<String> res, String tmp, int lhs, int rhs, int n)

{

if(lhs == n)

{

for(int i = 0; i < n – rhs; i++)

{

tmp += “)”;

}

res.add(tmp);

return ;

}

generate(res, tmp + “(”, lhs + 1, rhs, n);

if(lhs > rhs)

generate(res, tmp + “)”, lhs, rhs + 1, n);

}

}

人言未必皆真,听言只听三分。

采用递归树的思想实现java code

相关文章:

你感兴趣的文章:

标签云: