-
Notifications
You must be signed in to change notification settings - Fork 1
/
GenerateParentheses.java
73 lines (62 loc) · 2.1 KB
/
GenerateParentheses.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package com.leetcode;
import java.util.ArrayList;
import java.util.List;
public class GenerateParentheses {
/**
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1
Output: ["()"]
Time complexity: O(2^n), as there are 2^n possible combinations of ‘(‘ and ‘)’ parentheses.
Auxiliary space: O(n), as n characters are stored in the str array.
**/
//https://leetcode.com/problems/generate-parentheses/
// String is not passed as reference so no need to backtrack . Branch can end
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
backtrack(0,0,"",n,result);
return result;
}
public void backtrack(int open , int close , String s, int n , List<String> result){
if(close > open) return;
if(open > n) return;
if(open > 0 && open == close && open == n){
result.add(s);
}
backtrack(open+1 , close , s + '(' , n , result);
backtrack(open , close+1 , s + ')' , n , result);
}
}
}
/*
// Alternate
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
if(n <= 0){
return result;
}
generateParenthesis("", n , 0 , 0 , result);
//Collections.sort(result);//only to match
return result;
}
public void generateParenthesis(String subString , int n ,int open , int close , List<String> result) {
if(subString.length() == 2*n){
result.add(subString);
return;
}
if(subString.length() > 2*n){
return;
}
if(open < n){
generateParenthesis(subString+"(",n,open+1,close,result);
}
if(close < open){//important condition to remember
generateParenthesis(subString+")",n,open,close+1,result);
}
}
}
*/