Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Parenthesis {
- String str;
- int openCount;
- int closeCount;
- public Parenthesis(String str, int openCount, int closeCount) {
- this.str= str;
- this.openCount = openCount;
- this.closeCount = closeCount;
- }
- }
- class Solution {
- public List<String> generateParenthesis(int num) {
- List<String> result = new ArrayList<String>();
- generateParenthesisHelper(num, "", 0, 0, result);
- return result;
- }
- public void generateParenthesisHelper(int num, String curr, int openCount, int closeCount, List<String> result) {
- if((openCount == num) && (closeCount == num))
- result.add(curr);
- if(openCount < num) {
- generateParenthesisHelper(num, curr + "(", openCount+1, closeCount, result);
- }
- if(closeCount < openCount) {
- generateParenthesisHelper(num, curr + ")", openCount, closeCount+1, result);
- }
- }
- public List<String> generateParenthesisBreadthWise(int num) {
- List<String> result = new ArrayList<String>();
- Parenthesis initial = new Parenthesis("", 0, 0);
- Queue<Parenthesis> q = new LinkedList<>();
- q.add(initial);
- while(!q.isEmpty()) {
- Parenthesis p = q.poll();
- if(p.openCount == num && p.closeCount == num) {
- result.add(p.str);
- } else {
- if(p.openCount < num) {
- Parenthesis p1 = new Parenthesis(p.str + "(", p.openCount + 1, p.closeCount);
- q.add(p1);
- }
- if(p.openCount > p.closeCount) {
- Parenthesis p2 = new Parenthesis(p.str + ")", p.openCount, p.closeCount + 1);
- q.add(p2);
- }
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement