数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
1 <= n <= 8
难得一次排名有点高。。
解答成功: 执行耗时:1 ms,击败了95.79% 的Java用户 内存消耗:38.7 MB,击败了31.94% 的Java用户
Java
import java.util.LinkedList;
import java.util.List;
public class GenerateParentheses{
public static void main(String[] args) {
Solution solution = new GenerateParentheses().new Solution();
System.err.println(solution.generateParenthesis(5));
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
int max;
List<String> result = new LinkedList<>();
public List<String> generateParenthesis(int n) {
max = n;
dfs("",0,0);
return result;
}
void dfs(String s, int r,int l){
if (s.length() == max*2){
result.add(s);
return;
}
if (r<max){
dfs(s+"(",r+1,l);
}
if (l<r){
dfs(s+")",r,l+1);
}
return;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}
Rust
impl Solution {
pub fn generate_parenthesis(n: i32) -> Vec<String> {
let mut result = vec![];
Self::dfs(String::new(), 0, 0, n as usize, &mut result);
result
}
fn dfs(s: String, r: usize, l: usize, n: usize, result: &mut Vec<String>){
if (s.len() == 2*n ) {
result.push(s);
return;
}
if (r<n) {
let mut s = s.to_owned();
s.push('(');
Self::dfs(s, r+1, l, n, result);
}
if (l<r) {
let mut s = s.to_owned();
s.push(')');
Self::dfs(s, r, l+1, n, result);
}
}
}