给定一串数字和运算符,返回所有可能的结果,有效的运算符是+,

来源:互联网 发布:linux虚拟机kvm怎么用 编辑:程序博客网 时间:2024/05/01 20:33

本体源自leetcode

--------------------------------------------------------

思路:

递归: 遍历字符串遇到 运算符。递归求出运算符前面的结果。在递归求出运算符后的结果。在互相做运算

代码:

vector<int> diffWaysToCompute(string input) {        vector<int> result;        int len=input.size();        for(int i=0;i<len;i++){            char cur=input[i];            if(cur=='+'||cur=='-'||cur=='*'){                vector<int> pre=diffWaysToCompute(input.substr(0,i));  //计算运算符前半部分的结果                vector<int> post=diffWaysToCompute(input.substr(i+1));  //运算符后半部分的结果                for(auto i:pre){                    for(auto j: post){                        if(cur=='+'){                            result.push_back(i+j);                        }else if(cur=='-'){                            result.push_back(i-j);                        }else if(cur=='*'){                            result.push_back(i*j);                        }                    }                }            }        }        if(result.empty()){            result.push_back(stoi(input));        }        return result;    }

思路2 优化上述递归

1 递归包括很多重复运算。因此用动态规划来消除重复运算

用一个<string,vector<int>> map 做dp .

代码:

vector<int> diffWaysToCompute(string input) {        map<string,vector<int>> dp;        return compute(input,dp);    }    vector<int> compute(string input,map<string,vector<int>> &dp){        vector<int> result;        int len=input.size();        for(int i=0;i<len;i++){            char cur=input[i];            if(cur=='+'||cur=='-'||cur=='*'){                vector<int> pre;                vector<int> post;                string str=input.substr(0,i);                if(dp.find(str)!=dp.end()){                    pre=dp[str];                }else{                   pre=compute(str,dp);                 }                str=input.substr(i+1);                if(dp.find(str)!=dp.end()){                    post=dp[str];                }else{                    post=compute(str,dp);                }                for(auto i:pre){                    for(auto j: post){                        if(cur=='+'){                            result.push_back(i+j);                        }else if(cur=='-'){                            result.push_back(i-j);                        }else if(cur=='*'){                            result.push_back(i*j);                        }                    }                }            }        }        if(result.empty()){            result.push_back(stoi(input));        }        dp[input]=result;        return result;    }


阅读全文
0 0
原创粉丝点击