LeetCode-22.括號生成

地址:https://leetcode-cn.com/problems/generate-parentheses/

思路:一、搜索,通過對左括號位置的搜索,最終判斷其是否合法即可

二、DP,對於dp[n]='('+dp[i]+')'+dp[n-i-1]

Code:

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

/*
//DFS
class Solution {
public:
	int nn;
	bool boo[1005];
	vector<string> res;
	void DFS(int k,int l){
		if(k==nn+1){
			int t=0;
			string str="";
			for(int i=1;i<=2*nn&&t>=0;++i)
				if(boo[i]){
					++t;	str+='(';
				}else{
					--t;	str+=')';
				}
			if(!t)	res.push_back(str);
			return;
		}
		for(int i=l;i<2*nn;++i)
		{
			boo[i]=true;
			DFS(k+1,i+1);
			boo[i]=false;
		}
	}
	
    vector<string> generateParenthesis(int n) {
    	nn=n;
    	boo[1]=true;
		DFS(2,2);
		if(!n)	res.push_back("");
		return res; 
    }
};
*/

//dp
class Solution {
public:
    vector<string> generateParenthesis(int n) {
    	vector<string> dp[n+5];
    	dp[0]={""};
    	dp[1]={"()"};
    	for(int i=2;i<=n;++i)
    		for(int j=0;j<=i-1;++j)
    			for(auto s1:dp[j])
    				for(auto s2:dp[i-1-j])
    					dp[i].push_back('('+s1+')'+s2);
		return dp[n];
    }
};

int main()
{
	int n;
	Solution so;
	cin>>n;
	so.generateParenthesis(n);
	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章