Skip to content

Latest commit

 

History

History
220 lines (179 loc) · 4.55 KB

File metadata and controls

220 lines (179 loc) · 4.55 KB
comments edit_url
true

题目描述

正整数 n 代表生成括号的对数,请设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

 

示例 1:

输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

输入:n = 1
输出:["()"]

 

提示:

  • 1 <= n <= 8

 

注意:本题与主站 22 题相同: https://leetcode.cn/problems/generate-parentheses/

解法

方法一

Python3

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:
        def dfs(left, right, t):
            if left == n and right == n:
                ans.append(t)
                return
            if left < n:
                dfs(left + 1, right, t + '(')
            if right < left:
                dfs(left, right + 1, t + ')')

        ans = []
        dfs(0, 0, '')
        return ans

Java

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ans = new ArrayList<>();
        dfs(0, 0, n, "", ans);
        return ans;
    }

    private void dfs(int left, int right, int n, String t, List<String> ans) {
        if (left == n && right == n) {
            ans.add(t);
            return;
        }
        if (left < n) {
            dfs(left + 1, right, n, t + "(", ans);
        }
        if (right < left) {
            dfs(left, right + 1, n, t + ")", ans);
        }
    }
}

C++

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> ans;
        dfs(0, 0, n, "", ans);
        return ans;
    }

    void dfs(int left, int right, int n, string t, vector<string>& ans) {
        if (left == n && right == n) {
            ans.push_back(t);
            return;
        }
        if (left < n) dfs(left + 1, right, n, t + "(", ans);
        if (right < left) dfs(left, right + 1, n, t + ")", ans);
    }
};

Go

func generateParenthesis(n int) []string {
	var ans []string
	var dfs func(left, right int, t string)
	dfs = func(left, right int, t string) {
		if left == n && right == n {
			ans = append(ans, t)
			return
		}
		if left < n {
			dfs(left+1, right, t+"(")
		}
		if right < left {
			dfs(left, right+1, t+")")
		}
	}
	dfs(0, 0, "")
	return ans
}

TypeScript

function generateParenthesis(n: number): string[] {
    let ans = [];
    let dfs = function (left, right, t) {
        if (left == n && right == n) {
            ans.push(t);
            return;
        }
        if (left < n) {
            dfs(left + 1, right, t + '(');
        }
        if (right < left) {
            dfs(left, right + 1, t + ')');
        }
    };
    dfs(0, 0, '');
    return ans;
}

JavaScript

/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function (n) {
    let ans = [];
    let dfs = function (left, right, t) {
        if (left == n && right == n) {
            ans.push(t);
            return;
        }
        if (left < n) {
            dfs(left + 1, right, t + '(');
        }
        if (right < left) {
            dfs(left, right + 1, t + ')');
        }
    };
    dfs(0, 0, '');
    return ans;
};

Swift

class Solution {
    func generateParenthesis(_ n: Int) -> [String] {
        var ans = [String]()
        dfs(0, 0, n, "", &ans)
        return ans
    }

    private func dfs(_ left: Int, _ right: Int, _ n: Int, _ t: String, _ ans: inout [String]) {
        if left == n && right == n {
            ans.append(t)
            return
        }
        if left < n {
            dfs(left + 1, right, n, t + "(", &ans)
        }
        if right < left {
            dfs(left, right + 1, n, t + ")", &ans)
        }
    }
}