[LeetCode]--22. Generate Parentheses

简介: 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:[ "((()))", "(()())", "(())()",

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

用二叉树形象的表示这种关系。然后再把二叉树转化为代码的形式。因为二叉树的定义就是递归定义的,因此本题很明显应该使用递归的形式。

这里写图片描述

就如同遍历查找一棵二叉树一样,只不过这个是一个个往上加。

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

    private void dfs(List<String> res, String tem, int left, int right) {
        if (0 == left && 0 == right) {
            res.add(tem);
            return;
        } else if (left > 0)
            dfs(res, tem + '(', left - 1, right);
        if (left < right)
            dfs(res, tem + ')', left, right - 1);
    }

这种递归到最后自然就都加上去了。

目录
相关文章
|
索引
LeetCode 373. Find K Pairs with Smallest Sums
给定两个以升序排列的整形数组 nums1 和 nums2, 以及一个整数 k。 定义一对值 (u,v),其中第一个元素来自 nums1,第二个元素来自 nums2。 找到和最小的 k 对数字 (u1,v1), (u2,v2) ... (uk,vk)。
114 0
LeetCode 373. Find K Pairs with Smallest Sums
LeetCode 241. Different Ways to Add Parentheses
给定一个含有数字和运算符的字符串,为表达式添加括号,改变其运算优先级以求出不同的结果。你需要给出所有可能的组合的结果。有效的运算符号包含 +, - 以及 * 。
51 0
LeetCode 241. Different Ways to Add Parentheses
|
C++ 机器学习/深度学习
[LeetCode]--71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it. For example, path = “/home/”, =&gt; “/home” path = “/a/./b/../../c/”, =&gt; “/c” click to show corner cases. Corner Cases:
1034 0
[LeetCode]--409. Longest Palindrome
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters. This is case sensitive, for example “Aa” i
1127 0
[LeetCode]--263. Ugly Number
Write a program to check whether a given number is an ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 6, 8 are ugly while 14 is not ug
827 0
|
canal
[LeetCode]--125. Valid Palindrome
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, “A man, a plan, a canal: Panama” is a palindrome. “race a car”
1056 0
|
人工智能
[LeetCode]--136. Single Number
Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a linear runtime complexity. Could you implement it without
1196 0