java recursive solution


  • 0
    P
    public class Solution {
        int n;
        int temp1;
        int temp2;
        List<String> list = new ArrayList<>();
        int count = 0;
        public List<String> generateParenthesis(int n) {
            this.n = n;
            this.temp1 = 0;
            this.temp2 = 0;
            recursion(new StringBuilder());
            return list;
            
        }
        private void recursion(StringBuilder sb)
        {
            if(count == n*2)
            {
                list.add(new String(sb.toString()));
                return;
            }
            if(temp1<n)
            {
                sb.append("(");
                count++;
                temp1++;
                recursion(sb);
                sb.deleteCharAt(sb.length()-1);
                temp1--;
                count--;
            }
            if(temp2<temp1)
            {
                sb.append(")");
                count++;
                temp2++;
                recursion(sb);
                sb.deleteCharAt(sb.length()-1);
                temp2--;
                count--;
            }
            return;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.