Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save superlayone/5ab37493989befb86781 to your computer and use it in GitHub Desktop.

Select an option

Save superlayone/5ab37493989befb86781 to your computer and use it in GitHub Desktop.
构造n对括号的全部有效组合

##构造n对括号的全部有效组合

###思路

递归构造

  • 左括号:只要还有左括号,则加入
  • 右括号:只要右括号比左括号剩余的还多,则不构成非法,加入

###Code

    #include <iostream>
    #include <vector>
    #include <string>
    
    using namespace std;
    void GenerateParens(vector<vector<char>>& result,vector<char>& path,int left,int right,int count)
    {
    	if(left < 0 || right < 0)
    	{
    		return;
    	}
    	if(left == 0 && right == 0)
    	{
    		result.push_back(path);
    		return;
    	}
    	else
    	{
    		if(left > 0)
    		{
    			path[count] = '(';
    			GenerateParens(result,path,left-1,right,count+1);
    		}
    		if(right > left)
    		{
    			path[count] = ')';
    			GenerateParens(result,path,left,right-1,count+1);
    		}
    	}
    }
    vector<vector<char>> GenerateParens(int n)
    {
    	vector<char> path(n*2,'0');
    	vector<vector<char>> result;
    	GenerateParens(result,path,n,n,0);
    	return result;
    }
    int main()
    {
    	vector<vector<char>> result = GenerateParens(3);
    	for(int i = 0 ; i < result.size() ; ++i)
    	{
    		for(int j = 0 ; j < result[i].size() ; ++j)
    		{
    			cout<<result[i][j];
    		}
    		cout<<endl;
    	}
    	system("pause");
    	return 0;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment