1. 程式人生 > >leetcode之Generate Parentheses

leetcode之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:

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

程式碼:

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

vector<string> generateParenthesis(int n) {

	vector<string> s;
	if (n <= 0)return s;
	
	map<int, vector<string>> records;

	string s1 = "()";
	s.push_back(s1);
	records[1] = s;

	
	for (int i = 2; i <= n; i++) {

		vector<string> res;
		vector<string> v = records[i - 1];
		for (int j = 0; j < v.size(); j++) {
			string t = '(' + v[j] + ')';
			res.push_back(t);
		}

		int m = 1, n = i - 1;
		while (m <= n) {
			vector<string> v1 = records[m];
			vector<string> v2 = records[n];

			for (int k = 0; k < v1.size(); k++) {
				for (int o = 0; o < v2.size(); o++) {
					string s1 = v1[k]; string s2 = v2[o];
					string r1 = s1 + s2; string r2 = s2 + s1;

					if (r1 == r2) res.push_back(r1);
					else {
						res.push_back(r1);
						res.push_back(r2);
					}
				}
			}
				
			m++; n--;
		}
		sort(res.begin(), res.end());
		res.erase(unique(res.begin(), res.end()), res.end());

		records[i] = res;
	}

	return records[n];
}

int main() {

	vector<string> v = generateParenthesis(4);

	for (int i = 0; i < v.size(); i++) {
		cout << v[i]<<endl;
	}

	int m;
	cin >> m;
	return 0;
}

注意:

使用vector.erase(unique(),)的時候,先要排序,它才可以去除掉多餘重複元素。

建模的時候要考慮全面,多考慮別的情況,不要漏掉情況。