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:

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

分析:

这题是看了网上其他人的思路写的----------------

要想插入成功,需要符合两点要求:

1. 当左括号数量小于n时,可以插入左括号

2. 当右括号数量小于左括号时,可以插入右括号

3. 当左 = 右 = n时,我们可以将它push进容器内,作为一个最后结果中的一个情况

思路很简单,代码如下:



这里面总结了两个知识点:

1. string 与 string &区别

自己编写了例子:


我认为如果是引用的话,在函数内部可以对该值进行修改,但如果一开始写的类型是直接传值的话,那么函数内部对于该变量的修改无效,取决于它一开始被赋予的值。

另外有stackoverflow的一个例子

just because a reference is const inside a function, doesn't mean that the referand can't be modified via other references (the situation of one object having multiple references or pointers to it is called "aliasing"). Thus there is a different between passing a const reference, and passing a const value - in the case of the reference, the object might change after the call is made. In the case of the value, the callee has a private copy, which will not change.Since they do different things, C++ lets you choose which you want.There are consequences for performance either way - when you pass by value, a copy has to be made, which costs. But the compiler then knows that only your function can possibly have any references to that copy, which might allow other optimisations. ProcessStringByRef cannot load the contents of the string for printing until callback() has returned. ProcessStringByValue can, if the compiler thinks doing so is faster.Usually you care about the copy, not the order of execution of instructions, because usually the copy is way more expensive. So usually, you pass by reference where possible for objects that are non-trivial to copy. But the possibility of aliasing sometimes has really serious consequences for performance, by preventing certain optimisations even though no aliasing actually occurs. That's why "strict aliasing rules" exist, and the restrict keyword in C99.

2.我觉得这个代码神奇之处在与它的回跳,即在 findParenthesis 中 return;之后的操作。它在pop_back时还会回退到上一个状态,我觉得递归很神奇。。。。

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