1. 程式人生 > 實用技巧 >原生開機動畫流程

原生開機動畫流程

給定一個含有數字和運算子的字串,為表示式新增括號,改變其運算優先順序以求出不同的結果。你需要給出所有可能的組合的結果。有效的運算子號包含 +,-以及*。

示例1:

輸入: "2-1-1"
輸出: [0, 2]
解釋:
((2-1)-1) = 0
(2-(1-1)) = 2
示例2:

輸入: "2*3-4*5"
輸出: [-34, -14, -10, -10, 10]
解釋:
(2*(3-(4*5))) = -34
((2*3)-(4*5)) = -14
((2*(3-4))*5) = -10
(2*((3-4)*5)) = -10
(((2*3)-4)*5) = 10

來源:力扣(LeetCode)

class Solution {
public: vector<int> diffWaysToCompute(string input) { vector<int> res; for (int i = 0; i < input.size(); i++) { char ch = input[i]; if (ch == '+' || ch == '-' || ch == '*') { vector<int> a = diffWaysToCompute(input.substr(0
, i)); vector<int> b = diffWaysToCompute(input.substr(i+1 , input.size())); for (auto i: a) { for (auto j: b) { if (ch == '+') res.push_back(i + j); else if (ch == '-
') res.push_back(i - j); else res.push_back(i * j); } } } } if (res.empty()) res.push_back(atoi(input.c_str()));
     //c_str:Returns a pointer to an array that contains a null-terminated sequence of characters (i.e., a C-string) representing the current value of thestringobject.
     //atoi:Convert string to integer
return res;
    }
};