leetcode 241. Different Ways to Add Parentheses 分治法 C++

Different Ways to Add Parentheses
Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +, - and *.
這道題主要思想是Divide and Conquer 分治法
對于一個表達式 a - b, a與b均為表達式,計算a - b的結果 我們需要先知道a的結果與b的結果。對于知道加parentheses的題,只要對表達中的每一個運算符都做這樣的操作并遞歸,就可以得出所有可能結果,希望下面的例子可以幫助理解

                        2 * 3 - 4 * 5
                            /        \
              2 * (3 - 4 * 5)        ...
                        /     \
              (3 - 4 ) * 5     3 - (4 * 5)
               /    \
               3     4
class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> result;
        for (int i = 0; i < input.size(); i++) {
            char c = input[i];
            if (c == '+' || c == '-' || c == '*') {
                auto result1 = diffWaysToCompute(input.substr(0, i));
                auto result2 = diffWaysToCompute(input.substr(i + 1));
                for (int r1: result1) {
                    for (int r2: result2) {
                        if (c == '+')
                            result.push_back(r1 + r2);
                        else if (c == '-')
                            result.push_back(r1 - r2);
                        else
                            result.push_back(r1 * r2);
                    }
                }
            }
        }
        if (result.empty())
            result.push_back(atoi(input.c_str()));
        return result;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容