No241. Different Ways to Add Parentheses

来源:互联网 发布:萨洛蒙鞋怎么样知乎 编辑:程序博客网 时间:2024/06/05 02:00

一、题目描述

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.

二、主要思想

本题解法采用分治的思想,分治的思想主要是:

Thedivide-and-conquerstrategy solves a problem by:
1. Breaking it into subproblemsthat are themselves smaller instances of the sametype of problem
2. Recursively solving thesesubproblems
3. Appropriately combining theiranswers

将一个字符串按操作符号分为左子串,操作符号,右子串,按照题意即在遍历传入的字符串时,如果遇到+、-、*号时,则将字符串分为左右两个子串,并且递归调用函数本身对子串进一步处理。对于子串的每一个成员遍历,即子串所有可能得到的运算结果,对于每一个子串的结果用操作运算符把两个子串结合起来。如果遍历完整个字符串,但是没有运算符,即分到最末端只有数字时,则将数字的字符串形式转换为int型,用于上一步的操作符运算。

三、代码实现

class Solution {public:    vector<int> diffWaysToCompute(string input) {        vector<int> vec;        int len=input.length();        for(int i=0;i<len;i++){            if(input[i]=='+'||input[i]=='-'||input[i]=='*'){                vector<int> left = diffWaysToCompute(input.substr(0,i));                vector<int> right = diffWaysToCompute(input.substr(i+1));                for(int l:left){                    for(int r:right){                        if(input[i]=='+') vec.push_back(l+r);                        if(input[i]=='-') vec.push_back(l-r);                        if(input[i]=='*') vec.push_back(l*r);                    }                }            }        }        if(vec.empty())            vec.push_back(atoi(input.c_str()));        return vec;    }};

四、细节总结

1、获得字符串长度:string.length()或string.size()

2、截取一个字符串的一段子串:string.substr(start,length);两个参数分别为子串起始位置和子串的长度,或string.substr(start);一个参数表示从起始位置start到字符串结尾。

3、 atoi将字符串转化为int型:atoi(string.c_str())

4、c_str():生成一个const char*指针,指向以空字符终止的数组, 这个数组应该是string类内部的数组,c_str()返回的是一个临时指针,不能对其进行操作.

原创粉丝点击