每日算法之二十: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:

"((()))", "(()())", "(())()", "()(())", "()()()"

给出数字n,求出所有合法的表达式。

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

从上面的图片中我们可以很明显的看到,最后五条画黑线的就是最终的结果,其中左分支都是添加左括号,又分支都是添加右括号。

那么我们在什么情况下添加左括号呢?很明显,最多能添加n个左括号,在递归调用的时候,在能传递到最底层的共用字符串中先添加"(",然后left-1,递归调用就可以。

那什么时候添加右括号呢?当左括号个数大于右括号的个数时添加右括号。

那我们是先添加右括号还是先添加左括号呢?对于这个问题,认真想想其实是无所谓的,只会影响在vector中最后字符串的顺序而已。

下面是代码,难度主要在以下几个方面:

1.想到二叉树,想到递归实现。

2.递归函数的参数形式要考虑清楚才可以。

<span style="font-size:18px;">class Solution {
public:
   void dfs(vector<string> & resi,string temp,int left,int right)
    {
        if(left == 0 && right == 0)
        {
            resi.push_back(temp);
            return;
        }
        if(left>0)
            dfs(resi,temp+"(",left-1,right);
        if(left<right)
            dfs(resi,temp+")",left,right-1);
    }
    vector<string> generateParenthesis(int n) {
        vector<string> resi;
        if(n == 0)
            return resi;
        dfs(resi,"",n,n);
        return resi;
    }

};</span>

每日算法之二十:Generate Parentheses

时间: 2024-12-13 20:28:34

每日算法之二十:Generate Parentheses的相关文章

每日算法之二十八:Longest Valid Parentheses

Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. For "(()", the longest valid parentheses substring is "()", which has length = 2. Another example is &

每日算法之二十五:Divide Two Integers

Divide two integers without using multiplication, division and mod operator. 不使用乘法.除法和求模运算求两个数相除. class Solution { public: long long internalDivide(unsigned long long dividend,unsigned long long divisor) { if(dividend<divisor) return 0; int result =

每日算法之二十二:Swap Nodes in Pairs

Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, on

每日算法之二十六:Substring with Concatenation of All Words

变相的字符串匹配 给定一个字符串,然后再给定一组相同长度的单词列表,要求在字符串中查找满足以下条件的起始位置: 1)从这个位置开始包含单词列表中所有的单词,且每个单词仅且必须出现一次. 2)在出现的过程中不能出现其他的干扰单词. 3)出现的位置可能有多个. 4)单词的出现顺序不做要求. 下面是一个例子: S:"barfoothefoobarman" L:"foo","bar" 位置0是出现位置,:两个单词均出现仅出现一次,且没有干扰.同样位置9也

每日算法之二十九:Search in Rotated Sorted Array

在一个经过旋转后的有序数组中查找一个目标元素. Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1.

每日算法之二十三:Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is. You may not alter the values in the nodes, only nod

LLVM每日谈之二十 Everything &amp;&amp; Clang driver

作者:史宁宁(snsn1984) 最近在读<Getting Started with LLVM Core Libraries>,这是读的第一本LLVM的书,很多地方虽然讲的是自己知道的东西,但是也给人耳目一新的感觉,让人感觉之前有些不确定的东西,或者没有联系起来的知识点一下子贯通了,那感觉非常酸爽. 1.先谈谈题目里的Everything. LLVM每日谈之十六中,曾经提到过:Everything is a value.主要讲的是重要的LLVM IR的C++类都是Value的子类,同时在对IR

JAVA常见算法题(二十四)

package com.xiaowu.demo; //一个5位数,判断它是不是回文数.即12321是回文数,个位与万位相同,十位与千位相同. public class Demo24 { public static void main(String[] args) { f2(123454321); } // 方法一 public static void f1(int n) { if (n >= 10000 && n < 100000) { String s = String.va

JAVA常见算法题(二十八)

package com.forezp.util; import java.util.Arrays; /** * 两个int数组,都是从小到大的的排列,请合并为一个新的数组,也是从小到到大的排列, * 请写出性能最优的算法.<br> * * * * @author Administrator * */ public class ArrayDemo1 { public static void main(String[] args) { int[] a = { 1,3,5,7,9}; int[] b