22. Generate Parentheses

https://leetcode.com/problems/generate-parentheses/

brute force

gen all the permutation of parentheses, then validate them one by one

O(2^2n*n), ๆœ€ๅพŒไน˜ไธŠ n ๆ˜ฏ validate ็š„

2. dfs+backtracking

from "" to dfs gen string

ไพ็„ถๅฏไปฅ็•ซๅ‡บๆจน็‹€ๅœ–, ๆจน็‹€ๅœ–ๅพˆ้‡่ฆ

use adding

ไฝ†้€™้กŒๆ˜ฏๅฏไปฅๅœจไธญ้–“ๅฐฑๅˆคๆ–ทๆ˜ฏๅฆๅˆๆณ• n=3, ๅชๆœ‰ไธ‰ๅ€‹ๅทฆๆ‹ฌ่™Ÿไธ‰ๅ€‹ๅณๆ‹ฌ่™Ÿ

้€™้กŒๅช่ฆ้”ๅˆฐๅฆ‚ๆญคๆขไปถๅฐฑๅฏไปฅๅˆๆณ•(็ˆพไธ”ๅ› ็‚บ้€™้กŒๅชๆœ‰()) ๅทฆ้šจๆ™‚ๅฏไปฅๅŠ  ๅˆฅ่ถ…ๆจ™๏ผˆn=3๏ผ‰ ๅณไธ่ƒฝๅ…ˆๅ‡บ็พ, ๅทฆๅ€‹ๆ•ธ>ๅณๅ€‹ๆ•ธ

n > left > right, so n > right ๆ‰€ไปฅไธ็”จๅฏซ

time complexity:

This assumes you are doing constant amount of work in each call. In general, if you are doing k amount of work(outside calling functions recursively), then time complexity will be O(b^d * k)., O(2^d*k)

Taking the above example, n= 3 pairs. 2^0+2^1+2^2+..........+2^6.

Here b is 2, d is 6 as there are 6 levels.

https://leetcode.com/articles/generate-parentheses/

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        gen(0, 0, "", result, n);
        return result;
    }
    private void gen(int left, int right, String s, List<String> result, int n) {
        //termiator
        if (left == n && right == n) {
            result.add(s);
        }
        // drill down
        if (left < n) {
            gen(left + 1, right, s + "(", result, n);
        }
        if (left > right) {
            gen(left, right + 1, s + ")", result, n);
        }
    }
}

another way, use subtract

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        gen(n, n, "", result);
        return result;
    }
    private void gen(int left, int right, String s, List<String> result) {
        //termiator
        if (left == 0 && right == 0) {
            result.add(s);
            return;
        }
        // drill down
        if (left > 0) {
            gen(left - 1, right, s + "(", result);
        }
        if (right > left) {
            gen(left, right - 1, s + ")", result);
        }
    }
}

Last updated