首页 > 其他 > 详细

LeetCode() Different Ways to Add Parentheses

时间:2015-11-20 19:40:49      阅读:267      评论:0      收藏:0      [点我收藏+]

分治的思想:1分2治3合并解

这题最难的就是要想到 在运算符上分开。分治和递归是双胞胎啊!想不到啊想不到,不能再放纵自己了,眼睛干涩。

vector<int> diffWaysToCompute(string input) {
        vector<int> result;
        for (int i = 0; i < input.size(); i++) {
            char ch = input[i];
            if (ch == ‘+‘ || ch == ‘-‘ || ch == ‘*‘) {
                vector<int> lv = diffWaysToCompute(input.substr(0, i));
                vector<int> rv = diffWaysToCompute(input.substr(i+1));
                for (auto x : lv) {
                    for (auto y : rv) {
                        if (ch == ‘+‘) {
                            result.push_back(x+y);
                        } else if (ch == ‘*‘) {
                            result.push_back(x*y);
                        } else if (ch == ‘-‘) {
                            result.push_back(x-y);
                        }
                    }
                }
            }
        }
        if (result.empty()) {
            result.push_back(atoi(input.c_str()));
        }
        return result;

  

vector<int> diffWaysToCompute(string input) {
        vector<int> ans;
        bool pureNum=true;
        for (int i=0; i<input.length(); i++) 
            if (input[i]<‘0‘ || input[i]>‘9‘) {
                pureNum=false;
                vector<int> L=diffWaysToCompute(input.substr(0, i)), R=diffWaysToCompute(input.substr(i+1, input.length()-i-1));
                for (auto l : L)
                    for (auto r : R)
                        if (c==‘+‘) ans.push_back(l+r);
                        else if (c==‘-‘) ans.push_back(l-r);
                        else if (c==‘*‘) ans.push_back(l*r);
            }

        if (pureNum)
            ans.push_back(atoi(input.c_str()));
        return ans;
    }

技术分享

这是一个二叉树啊,递归就是解决二叉树的。应该形成固定思维啊暂时。

LeetCode() Different Ways to Add Parentheses

原文:http://www.cnblogs.com/yanqi110/p/4981742.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!