算法設計課作業系列3
Different Ways to Add Parentheses
題目展示
iven 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 *.
Example 1
Input: “2-1-1”.
((2-1)-1) = 0
(2-(1-1)) = 2
Output: [0, 2]
Example 2
Input: “2*3-4*5”
(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
Output: [-34, -14, -10, -10, 10]
解題過程
參考網址
Different Ways to Add Parentheses 表達式加括號
這裏說一點,參考只是參考思路而已,而不是參考代碼,我發現自己寫題很大的問題就是獨立思考無法想出正確的解題方法,並且對現在學習的分治只停留在理論的層次上,還沒有深入去了解真正的含義,因此當我查到了什麼算法時,很容易就可以完成,但是卻無法自己去設計出一個行之有效的算法。
思路分析
很明顯這是一個涉及分治算法的問題(因爲在分治算法大類下~),題目要求所有可能的結果,盲目去自己找規律是沒有用的,而計算機最擅長的就是計算,因此,我們可以讓計算機幫忙去把所有可能列舉出來,從而完成。
看到題目,既然是加括號的問題,就要考慮括號加在哪,我們可以從最簡單的地方開始,也就是沒有算術運算符,這時候,不需要任何括號,直接值本身就是答案;當有一個運算符時,也很簡單,也是直接算出結果即可;擴展到兩個算術運算符呢?我們可以這樣考慮,對於每一個運算符,分成左右兩個部分,這時候就可以將一個大問題劃分成兩個子問題,而最終的問題將回到沒有運算符的情況(因爲一個運算符也是可以拆分的)。因此思路就來了,對於每個運算符,算出其左右可能的取值,並對左右的取值依次互相做運算,最後也就可以毫無遺漏獲得所有的取值。
源代碼
#include<vector>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
class Solution {
public:
vector<int> diffWaysToCompute(string input) {
vector<int> result;
int cnt = 0;
for (int i = 0; i < input.size(); i++) {
if (input[i] == '-' || input[i]== '+' || input[i] == '*') {
cnt++;
vector<int> left = diffWaysToCompute(input.substr(0, i));
vector<int> right = diffWaysToCompute(input.substr(i + 1));
for (int j = 0; j < left.size(); j++) {
for (int k = 0; k < right.size(); k++) {
switch (input[i]) {
case '+':
result.push_back(left[j] + right[k]);
break;
case '-':
result.push_back(left[j] - right[k]);
break;
case '*':
result.push_back(left[j] * right[k]);
break;
}
}
}
}
}
if (cnt == 0) {
result.push_back(std::stoi(input));
cout << input << ' ' << stoi(input) << endl;
// cout << result.size() << ' ';
}
sort(result.begin(), result.end());
return result;
}
};