leetcode 22,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:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”
題意:
給出括弧對數,任意組合,找出所有滿足括弧匹配原則的字串。
思路:
考慮出規律即可,規律就是我們要在字串的任意時刻保證左括弧“(”的數目大於右括弧的數目“)”即可。^_^
代碼:
class Solution {public: void addRetStr(int leftNum, int rightNum, string s, vector<string>&ivecs){ if(leftNum == 0 && rightNum == 0){ ivecs.push_back(s); } //左括弧數目等於右括弧數目立即添加左括弧來保證規則。 if(leftNum == rightNum){ s += "("; addRetStr(leftNum-1, rightNum, s, ivecs); }else{ if(leftNum > 0){ //注意這裡參數必須是new string而不能s += "("然後傳遞參數s,因為還有別的string要用s。 string new_str = s + "("; addRetStr(leftNum-1, rightNum, new_str, ivecs); } if(rightNum > 0){ string new_str = s + ")"; addRetStr(leftNum, rightNum-1, new_str, ivecs); } } } vector<string> generateParenthesis(int n) { string s; vector<string>ret; addRetStr(n, n, s, ret); return ret; }};
雖然很晚了強迫症還是要寫完今天的部落格,哈哈
最後 祝自己20歲生日快樂^_^,感謝父母帶我來這個世界,感謝我的每一位家人,朋友,加油
life's battle doesn't always go to the stronger or faster man
but sooner or later the man who wins
is the man who thinks he can...