Categories
不学无术

LeetCode 22. Generate Parentheses

题目:https://leetcode.com/problems/generate-parentheses/
思路:
主要问题是,什么时候可以加左括号,什么时候可以加右括号。这需要判断当前已有字串的左右括号个数,有以下三种情况:

  1. 如果当前左括号的数目等于(也可以说小等于,不过小于的情况是出错了)右括号了,比如(),那只能加左括号;
  2. 如果当前左括号数目大于右括号,比如(((),那么
    1. 如果还有剩左括号的配额,可以加左括号(新分支了);
    2. 否则只能加右括号(在原有答案上操作即可);

代码:

class Solution {
public:
	vector<string> generateParenthesis(int n) {
		vector<string> results;
		vector<pair<int, int>> parSize;
		// If size('(') <= size(')'), we can only append '(';
		// Else, append '(' or ')' if it doesn't reach the quota
		int count = 1;
		results.push_back(string("("));
		parSize.push_back(pair<int, int>(1, 0));
		int resultSz;
		while (count < n * 2) {
			resultSz = results.size();
			int lsize, rsize;
			for (int i = 0; i<resultSz; i++) {
				lsize = parSize[i].first;
				rsize = parSize[i].second;
				if (lsize <= rsize) {
					results[i] += "(";
					parSize[i].first++;
				}
				else {
					if (lsize < n) {
						string cpStr = results[i] + "(";
						pair<int, int> cpSz = parSize[i];
						cpSz.first++;
						results.push_back(cpStr);
						parSize.push_back(cpSz);
					}
					results[i] += ")";
					parSize[i].second++;
				}
			}
			count++;
		}
		return results;
	}
};

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.