LINTCODE——计算最大值

来源:互联网 发布:网络管理规章制度 编辑:程序博客网 时间:2024/06/16 14:34

LINTCODE——计算最大值

给一个字符串类型的数字, 写一个方法去找到最大值, 你可以在任意两个数字间加 + 或 *

您在真实的面试中是否遇到过这个题? Yes
样例
eg1:给出 str = 01231, 返回 10 ((((0 + 1) + 2) * 3) + 1) = 10 我们得到了最大值 10
eg2:给出 str = 891, 返回 73 因为 8 * 9 * 1 = 72 和 8 * 9 + 1 = 73, 所以73是最大值

这个题目的题意有一点点小问题,例如eg2:891,我如果是8*(9+1)等于80大于73啊,所以题目的意思应该是添加运算符之后,按照从左到右的顺序计算数值,就是eg1的形式,自动添加小括号,那么题目就变得简单多了,利用dfs每调用一次,计算个数值,然后再次调用dfs就好了,直到str的末尾

class Solution {private:    int res = 0;public:    /*     * @param : the given string     * @return: the maximum value     */    int calcMaxValue(string &str) {        // write your code here        if(str.empty())            return 0;        int n = str.size();        dfs(str, 1,str[0]-'0');        return res;    }    void dfs(const string &str, int index,int ans)    {        if(index == str.size())        {            //只取最大值            res = max(res,ans);            return;        }        dfs(str, index+1,str[index]-'0'+ans );        dfs(str, index+1, (str[index]-'0')*ans);    }};