声明:原题目转载自LeetCode,解答部分为原创
Problem :
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 *
.
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]
Solution:
思路:比较常见的分治题目之一,以字符串的操作符为界,将字符串分成两个子字符串,求运算结果,以此类推,极限情况是字符串中只有一个字符,用atoi()函数转换为int类型并存入result容器。
代码如下:
#include
#include
#include
using namespace std;
class Solution {
public:
vector
diffWaysToCompute(string input) {
vector
result; int size = input.size(); if(input.size() == 1) { int temp_num = atoi(&input[0]); result.push_back(temp_num); } for(int i = 0 ; i < size ; i ++) { char temp_letter; temp_letter = input[i]; if(temp_letter == '+' || temp_letter == '-' || temp_letter == '*' || temp_letter == '/') { string part_0, part_1; part_0 = input.substr(0, i); part_1 = input.substr(i + 1, input.size()); vector
result_0, result_1; result_0 = diffWaysToCompute(part_0); result_1 = diffWaysToCompute(part_1); for(int i = 0 ; i < result_0.size() ; i ++) { for(int j = 0 ; j < result_1.size() ; j ++) { int num_0 = result_0[i]; int num_1 = result_1[j]; // int num_0 = atoi(result_0[i]); // int num_1 = atoi(result_1[j]); if(temp_letter == '+') { result.push_back(num_0 + num_1); } else if(temp_letter == '-') { result.push_back(num_0 - num_1); } else if(temp_letter == '*') { result.push_back(num_0 * num_1); } else if(temp_letter == '/') { result.push_back(num_0 / num_1); } } } } } return result; } }; int main() { Solution text; string input = "2*3-4*5"; vector
output = text.diffWaysToCompute(input); // cout << "count :: " << output.size() << endl; for(int i = 0 ; i < output.size() ; i ++) { cout << output[i] << endl; } return 0; }