generate-parentheses.dart (1104B)
1 //Given a number n return all combinations of valid parenthesis 2 //with n sets of parentheses. 3 //To do this I used recursion to follow each branch until 4 //they ended and then returned each set of valid parenthesis. 5 //The time complexity of this code is 2^n where n is the number 6 //of sets of parenthesis to generate. 7 //Time: 273ms Beats: 47.50% 8 //Memory: 143.2MB Beats: 10% 9 class Solution { 10 List<String> generateParenthesis(int n) { 11 return parenthesis(n , n); 12 } 13 List<String> parenthesis(int left , int right){ 14 if(left == 0 && right == 0){ 15 return [""]; 16 } 17 List<String> return_ls = []; 18 if(left != 0){ 19 List<String> l1 = parenthesis(left - 1 , right); 20 for(int i = 0 ; i < l1.length ; ++i){ 21 l1[i] = '(' + l1[i]; 22 return_ls.add(l1[i]); 23 } 24 } 25 if(right != 0 && left < right){ 26 List<String> r1 = parenthesis(left , right - 1); 27 for(int i = 0 ; i < r1.length ; ++i){ 28 r1[i] = ')' + r1[i]; 29 return_ls.add(r1[i]); 30 } 31 } 32 return return_ls; 33 } 34 }