Leetcode22.Generate_Parentheses

回溯法
时间复杂度:O( N h ( N ) Nh(N) )=O( N C 2 N N N + 1 N\frac{C_{2N}^{N}}{N+1} )=O( 4 n n 1 2 \frac{4^n}{n^{\frac{1}{2}}} )
时间复杂度分析:对于n对括号生成的序列数,设为h(n)
生成n对有效括号排列数的计算
可以抽象为:在任意k<n总有开括号数小于等于闭括号数,且当k=n时,开括号数等于闭括号数的条件下有多少种括号排列方式。
继而可以抽象为:对n个0和n个1的排列组合,对任意k<=n总有0的个数小于等于1的个数。
这类排列数就是卡塔兰数,其递推式为:
h ( n ) = i = 0 n h ( i ) h ( n 1 i ) ( h ( 0 ) = 1 , h ( 1 ) = 1 ) h(n)=\sum^{n}_{i=0}{h(i)*h(n-1-i)}(h(0)=1,h(1)=1)
其通式为
h ( n ) = C n 2 n n + 1 h(n) = \frac{C^{2n}_{n}}{n+1} , h ( n ) 4 n n 3 2 h(n)≈\frac{4^n}{n^{\frac{3}{2}}}
余下对卡塔兰数与 O ( h ( N ) ) O(h(N)) 的详细数学分析见下网页
https://blog.csdn.net/qq_42263831/article/details/82957308
e.g.
h ( 1 ) = 1 h(1)=1
h ( 2 ) = h ( 1 ) h ( 0 ) + h ( 0 ) h ( 1 ) = 2 h(2) = h(1)h(0)+h(0)h(1)=2
h ( 3 ) = h ( 2 ) h ( 0 ) + h ( 1 ) ( 1 ) + h ( 0 ) h ( 2 ) = 5... h(3)=h(2)h(0)+h(1)(1)+h(0)h(2)=5...
C++代码:

class Solution {
public:
	vector<string> result;
	vector<string> generateParenthesis(int n) {
		generate("", n, 0, 0);
		return result;
	}
	void generate(string s, int total, int left, int right) {
		if (right == total)
		{
			result.push_back(s);
		}
		if (left > right)
		{
			string temp = s + ')';
			generate(temp, total, left, right + 1);
		}
		if (left < total)
		{
			string temp = s + '(';
			generate(temp, total, left + 1, right);
		}
	}
};

猜你喜欢

转载自blog.csdn.net/qq_42263831/article/details/82954637