[Day11]22. Generate Parentheses

Late again.
MEDIUM level again. But this one is interesting.

DESCRIPTION:
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

ANALYSIS:
One thing we know about this problem is to lengthen it one by one. If you are a seasonal player, maybe you would find that 'Oh! Recursion!'. But I am not one of those ones. So, I ask SLF again, and he told me to use 'classified discussion' and 'recursion'.

SOLUTION:

According to the hint given by SLF, code by myself, around 1 hour:

package leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class p22_Generate_Parentheses {

    static List results = new ArrayList();
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (true) {
            int n = scanner.nextInt();
            List results = new ArrayList();
            results = generateParenthesis(n);
            for (int i = 0; i < results.size(); i++) {
                System.out.println(results.get(i));
            }
            System.out.println("--------------");
        }
    }

    public static List generateParenthesis(int n) {
        String s = "";
        addOne(s, n);
        return results;
    }

    private static void addOne(String s, int n) {
        if (s.length() < n * 2) {
            int[] lr = countlr(s);
            int l = lr[0];
            int r = lr[1];
            if (l == r) {
                addOne(s + '(', n);
            } else if (l == n) {
                addOne(s + ')', n);
            } else if (l > r) {
                addOne(s + '(', n);
                addOne(s + ')', n);
            }
        } else {
            results.add(s);
        }
    }

    private static int[] countlr(String string) {
        int countl = 0;
        int countr = 0;
        for (int i = 0; i < string.length(); i++) {
            if (string.charAt(i) == '(')
                countl++;
            else
                countr++;
        }
        int[] result = { countl, countr };
        return result;
    }
}

And this is the top solution on SLF'S JianShu, whose idea enlighten me.

    public List generateParenthesis(int n) {
        List list = new ArrayList();
        backtrack(list, "", 0, 0, n);
        return list;
    }


    public void backtrack(List list, String str, int open, int close, int max){
        //若长度达到 max*2 说明完整了,加入到 list 里面
        if(str.length() == max*2){
            list.add(str);
            return;
        }
        //当 open

你可能感兴趣的:([Day11]22. Generate Parentheses)