Skip to content

Latest commit

 

History

History
59 lines (42 loc) · 1002 Bytes

20220331.md

File metadata and controls

59 lines (42 loc) · 1002 Bytes

Algorithm

22. Generate Parentheses

Description

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2:

Input: n = 1
Output: ["()"]

Constraints:

  • 1 <= n <= 8

Solution

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();
        backtrack(list,"",0,0,n);
        return list;
    }
     public void backtrack(List<String> list,String str, int open ,int close,int max){
         if(str.length()==max*2){
             list.add(str);
             return;
         }
         if(open<max){
             backtrack(list,str+"(",open+1,close,max);
         }
         if(close<open){
             backtrack(list,str+")",open,close+1,max);
         }
     }
}

Discuss

Review

Tip

Share