leetcode 22,leetcode

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.