算法——Week3

22. 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:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]


解题思路

  1. 考虑将正确结果按顺序编号,以上面的结果为例:

    ((())) (:123 ):456
    (()()) (:124 ):356
    (())() (:125 ):346

    发现如下规律:
    (1)left第一个一定是1,right最后一个一定是n
    (2)两个序列都是递增的
    (3)两个序列,相同位置的值,left<right
    利用next_permutation()函数求出所有排列,找出其中满足条件的,即求出了结果。
    但是这种方法的时间复杂度非常大,输入数字较大时会超时。
    代码如下:

class Solution {
public:
        int Sum(int *a, int *b, int n) {
        int result1 = 0;
        int result2 = 0;
        for(int i = 0; i < n - 1; i++) {
            result1 = result1 + a[i];
            result2 = result2 + b[i];
        }
        return result2 + n - result1 - 1;
    }
    vector<string> generateParenthesis(int n) {
        vector<string> s;
        int sum = 0;
        for(int i = 1; i <= n; i++) {
            sum = sum + i;
        }
        vector<int> temp_v(n*2 - 2);
        for(int i = 0; i < 2 * n - 2; i++) {
            temp_v[i] = i + 2;
        }
        int* temp=new int[temp_v.size()];
        for(int i=0;i<temp_v.size();i++)
            temp[i]=temp_v.at(i);
        while(next_permutation(temp, temp + n * 2 - 2)) {
            int temp1[n];
            int temp2[n];
            temp1[0] = 1;
            temp2[n-1] = 2*n;
            for(int i = 1; i < n; i++) {
                temp1[i] = temp[i-1];
            }
            for(int i = 0; i < n - 1; i++) {
                temp2[i] = temp[i + n - 1];
            }
            bool tag = true;
            for(int i = 0; i < n - 1; i++) {
                if(temp1[i] > temp1[i+1] || temp2[i] > temp2[i+1] || temp1[i] > temp2[i]) {
                    tag = false;
                }
                if(temp1[i] > temp2[i]) {
                    tag = false;
                }
            }
            if(tag) {
            	
                if(Sum(temp1, temp2, n) >= n) {
                    string p;
                    vector<int> tag(2*n);
                    for(int i = 0; i < n; i++) {
                        tag[temp1[i] - 1] = 0;
                        tag[temp2[i] - 1] = 1;
                    }
                
                    for(int i = 0; i < 2*n; i++) {
                        if(tag[i] == 0) {
                            p.push_back('(');
                        }
                        else {
                            p.push_back(')');
                        }
                    }
                    s.push_back(p);
                }
            }
        }
        string str;
        for(int i = 0; i < n; i++) {
        	str.push_back('(');
		}
		for(int i = 0; i < n; i++) {
        	str.push_back(')');
		}
		s.push_back(str);
        return s;
    }
};

猜你喜欢

转载自blog.csdn.net/melwx/article/details/85260134