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

给表达式添加运算符

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

递归求解

alt

public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param num string字符串 
     * @param target int整型 
     * @return string字符串vector
     */
    vector<string> addOpt(string num, int target) {
        // write code here
        vector<string> res;
        string add, sub, mul;
        int len = num.size();
        if(len <= 1){
            return res;
        }
        
        int tmp = 0;
        add_func(num, res, add, tmp, target, 0, '+');
        tmp = 0;
        add_func(num, res, mul, tmp, target, 0, '*');
        tmp = 0;
        add_func(num, res, sub, tmp, target, 0, '-');
        
        return res;
    }
    
    void add_func(string num, vector<string>& res, string& str, int& cal, int target, int index, char symbol){
        if(index == 0){
            cal = num[index] - '0';
            str += num[index];
            index++;
            add_func(num, res, str, cal, target, index, symbol);
            return;
        }
        if(index == num.size()){
            if(cal == target){
                res.push_back(str);
            }
            return;
        }
        switch(symbol){
            case '+':
                cal += num[index] - '0';
                break;
            case '*':
                cal *= num[index] - '0';
                break;
            case '-':
                cal -= num[index] - '0';
                break;
            default:
                break;
        }
        
        str += symbol;
        str += num[index];
        index++;
        add_func(num, res, str, cal, target, index, symbol);
    }
};
全部评论

相关推荐

有工作后先养猫:太好了,是超时空战警,我们有救了😋
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务