题解 | #给表达式添加运算符#

给表达式添加运算符

http://www.nowcoder.com/practice/fdaee292bdaf4a7eb686c8ce72b2f3e1

介于数据规模较小,暴力dfs求解即可。

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param num string字符串 
     * @param target int整型 
     * @return string字符串vector
     */
    vector<string> ans;
    map<char,int> opt = {{'+',1},{'-',1},{'*',2}};
    void dfs(string num,int target,int start,string temp){
        if(start == num.size()){
            stack<int> num_stack;
            stack<char> opt_stack;
            int i = 0;
            while(!(num_stack.size() == 1 && i == temp.size())){
                if(temp[i] <= '9' && temp[i] >= '0'){
                    num_stack.push(temp[i] - '0');
                    ++i;
                }
                else{
                    if(opt_stack.empty()){
                        opt_stack.push(temp[i]);
                        ++i;
                    }
                    else{
                        if((opt_stack.size() == 1 && i == temp.size() )|| opt[opt_stack.top()] >= opt[temp[i]]){
                            int b = num_stack.top();
                            num_stack.pop();
                            int a = num_stack.top();
                            num_stack.pop();
                            if(opt_stack.top() == '+')
                                num_stack.push(a + b);
                            else if(opt_stack.top() == '-')
                                num_stack.push(a - b); 
                            else
                                num_stack.push(a * b);
                            opt_stack.pop();
                        }
                        else{
                            opt_stack.push(temp[i]);
                            ++i;
                        }
                    }
                }
            }
            if(num_stack.top() == target)
                ans.push_back(temp);
            return;
        }
        dfs(num,target,start + 1,temp + '+' + num[start]);
        dfs(num,target,start + 1,temp + '-' + num[start]);
        dfs(num,target,start + 1,temp + '*' + num[start]);
    }
    vector<string> addOpt(string num, int target) {
        // write code here
        string temp(1,num[0]);
        dfs(num,target,1,temp);
        return ans;
    }
};
全部评论

相关推荐

不愿透露姓名的神秘牛友
2024-12-30 18:02
程序员牛肉:1.可以标记一下自己的学校是985,有一些hr可能没想到你这个院校是985的。 2.简历所呈现出来的能力还是有点差的,苍穹外卖+黑马点评。这在java技术域里面也就是刚学三四个月的样子,大厂现在招人少,小厂又更加希望你能直接过来干活。就你简历上呈现出来的能力,确实是有点难找,肉眼可见的不懂技术。 第一个项目中:简单的使用redis也算是亮点嘛?使用jwt,threadlocal也算是亮点?你不就是调了几个包嘛?Nginx作为服务器也能写出来,这不是前端的活嘛? 第二个项目中:分布式锁+mq消息队列+Lua队列。真没啥好问的。属于面试官看一眼就阳痿的简历,没有任何想提问的欲望。 我给你建议是好好的挖一挖这个项目吧,其实苍穹外卖和黑马点评这两个项目很不错了,只不过是太烂大街了导致面试官没啥问的兴趣,所以不太推荐写简历上。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务