Skip to content

Files

Latest commit

Sep 28, 2022
5fe6552 · Sep 28, 2022

History

History
63 lines (45 loc) · 1.08 KB

20221029.md

File metadata and controls

63 lines (45 loc) · 1.08 KB

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 left ,int right,int n){
         // 正好遍历结束,结果放入队列
         if(str.length()==n*2){
             list.add(str);
             return;
         }
         // 左括号<n
         if(left<n){
             backtrack(list,str+"(",left+1,right,n);
         }
         // 右括号<左括号
         if(right<left){
             backtrack(list,str+")",left,right+1,n);
         }
     }
}

Discuss

Review

Tip

Share