WEEK#13 Divide and Conquer_Different Ways to Add Parentheses

Description of the 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: "2x3-4x5"

(2x(3-(4x5))) = -34
((2x3)-(4x5)) = -14
((2x(3-4))x5) = -10
(2x((3-4)x5)) = -10
(((2x3)-4)x5) = 10
Output: [-34, -14, -10, -10, 10]


Solution1 : Divide and Conquer (Wrong Answer 19/25)

Decompose the problem into smaller and similar parts.
Realizing that the result is certain when there are 2 operators, so we want to make whatever input we get into the pattern of 2 operators.
For example, an expression of 4 operators A op B op C op D can be divided into expressions of 3 operators:

  1. (A op B) op C op D
  2. A op (B op C) op D
  3. A op B op (C op D)

Which can be furtherly divided into expressions of 2 operators:
Take 1 for example:
1.1 ((A op B) op C) op D
1.2 (A op B) op (C op D)

Whose result would then be unique.

class Solution {
public:
    vector<int> diffWaysToCompute(string input) {

        vector<int> results;
        vector<int> operators;
        vector<char> operations;
        vector<string> expressions;

        bool flag; // check if the input has only one operator.
        for (int i = 0; i < input.size(); i++) {
            if (input[i] == '+' || input[i] == '-' || input[i] == '*') {
                flag = false;
                break;
            }
            flag = true;
        }
        if (flag) {
            results.push_back(stoi(input));
            return results;
        }
        int LastBegin = 0; // begin index of the last operator
        string oprt = "";
        for (int i = 0; i < input.length(); i++) { // get all operators and operations.
            if (input[i] == '+' || input[i] == '-' || input[i] == '*') {
                operations.push_back(input[i]);
                oprt = input.substr(LastBegin, i-LastBegin);
                operators.push_back(stoi(oprt));
                LastBegin = i + 1;
            }
        }
        oprt = input.substr(LastBegin, input.length() - LastBegin);
        operators.push_back(stoi(oprt));
        DivideAndConquer(operators, operations, results, expressions);

        return results;
    }

    void DivideAndConquer(vector<int> operators, vector<char> operations, vector<int>& results, vector<string>& expressions) {
        int result;
        if (operators.size() == 2) { // unique result
            stringstream ss;
            string expression = "";
            if (operations[0] == '+') {
                result = operators[0] + operators[1];
                ss << (operators[0]);
                ss << '+';
                ss << (operators[1]);
                expression = ss.str();
            }
            else if (operations[0] == '-') {
                result = operators[0] - operators[1];
                ss<<(operators[0]);
                ss<< '-';
                ss<<(operators[1]);
                expression = ss.str();
            }
            else if (operations[0] == '*') {
                result = operators[0] * operators[1];
                ss << (operators[0]);
                ss << '*';
                ss << (operators[1]);
                expression = ss.str();
            }

            if (!FindExpression(expression, expressions)) {
                results.push_back(result);
                expressions.push_back(expression);
            }
            return;
        }


        vector<int> NextRoundOperators;
        vector<char> NextRoundOperations;

        for (int i = 0; i < operations.size(); i++) { // calculate in different orders
            NextRoundOperations.clear();
            NextRoundOperators.clear();
            if (operations[i] == '+')
                result = operators[i] + operators[i + 1];
            else if (operations[i] == '-')
                result = operators[i] - operators[i + 1];
            else if (operations[i] == '*')
                result = operators[i] * operators[i + 1];
            for (int j = 0; j< operators.size(); j++) {
                if (j != i && j != i + 1)
                    NextRoundOperators.push_back(operators[j]);
            }
            vector<int>::iterator it = NextRoundOperators.begin();
            int temp = i;
            while (temp--)
                it++;
            NextRoundOperators.insert(it, result);
            for (int k = 0; k < operations.size(); k++) {
                if (k != i)
                    NextRoundOperations.push_back(operations[k]);
            }
            DivideAndConquer(NextRoundOperators, NextRoundOperations, results, expressions);
        }

    }

    bool FindExpression(string exp, vector<string> exps) {
        for (int i = 0; i < exps.size(); i++) {
            if (exp == exps[i])
                return true;
        }
        return false;
    }

};

Solution 2

Every time we encounter an operator, record it and divide the expression into 2 parts [exp1 op exp2] by the operator.
For each part, which is also an expression, would have its calculating result, so the expression [exp1 op exp2] would also have its result.

class Solution {
public:
    vector<int> diffWaysToCompute(string input) {
        vector<int> result;
        int size = input.size();
        for (int i = 0; i < size; i++) {
            char cur = input[i];
            if (cur == '+' || cur == '-' || cur == '*') {
                // Split input string into two parts and solve them recursively
                vector<int> result1 = diffWaysToCompute(input.substr(0, i));
                vector<int> result2 = diffWaysToCompute(input.substr(i+1));
                for (auto n1 : result1) {
                    for (auto n2 : result2) {
                        if (cur == '+')
                            result.push_back(n1 + n2);
                        else if (cur == '-')
                            result.push_back(n1 - n2);
                        else
                            result.push_back(n1 * n2);    
                    }
                }
            }
        }
        // if the input string contains only number
        if (result.empty())
            result.push_back(atoi(input.c_str()));
        return result;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,723评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,080评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,604评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,440评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,431评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,499评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,893评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,541评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,751评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,547评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,619评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,320评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,890评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,896评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,137评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,796评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,335评论 2 342

推荐阅读更多精彩内容

  • 紫发男子犹豫了下问道:“八百源界石,你派的人,把握如何?” “每次动手应该有五成把握。”老者说道,“连续失败三次任...
    im喵小姐阅读 273评论 0 0
  • 繁华靡丽都如梦,过眼还成空。由来衣冠拟王侯,更不道余生一盏灯幽。 恨无铁手擎天裂,一卷文如雪。寸心如月遣谁知,总是...
    温犹凉阅读 681评论 2 5
  • 【执子之手】儿童学习力六期 践行记录20170630Day46 1.指读了山居秋暝、问刘十九,宝宝认识了空山新雨后...
    cancan妈阅读 169评论 0 0
  • 最近 一条以【友情】为主线的小船 以迅雷不及掩耳盗铃响叮当之势 从微博刷到微信 从职业内容演变成行业内幕 霸屏之势...
    956366d1563c阅读 264评论 0 0