What's wrong with my Code? Why some result have duplicate result,some not?


  • 0
    T

    class Solution {
    public:
    vector<int> diffWaysToCompute(string input) {
    vector<int> nums;
    vector<char> ops;
    vector<int> result;
    if(input.size()<1)
    return result;

        int tmp = 0;
        for(int i = 0;i<input.size();i++)
        {
            char ch = input.at(i);
            if(ch>='0'&&ch<='9')
            {
                tmp = tmp*10 + ch-'0';
            }
            else if(ch=='+' || ch=='-' || ch=='*')
            {
                nums.push_back(tmp);
                tmp = 0;
                
                ops.push_back(ch);
            }
        }
        
        nums.push_back(tmp);
        tmp = 0;
        
        if(ops.size()==0)
            return nums;
        
        generateResult(nums,ops,result);
        sort(result.begin(),result.end());
        //result.erase(unique(result.begin(), result.end()), result.end());
        
        return result;
    }
    
    void generateResult(vector<int> &num, vector<char> &ops,vector<int> &result)
    {
        if(ops.size()==1)
        {
            switch(ops.at(0))
            {
                case '+':
                    result.push_back(num.at(0) + num.at(1));
                    return;
                case '-':
                    result.push_back(num.at(0)-num.at(1));
                    return;
                case '*':
                    result.push_back(num.at(0)*num.at(1));
                    return;
            }
            return;
        }
        
        for(int i = 0;i<ops.size();i++)
        {
            vector<int> new_num(num.begin(),num.end());
            vector<char> new_ops(ops.begin(),ops.end());
            switch(ops.at(i))
            {
                case '+':
                    new_num.at(i+1) = new_num.at(i) + new_num.at(i+1);
                    break;
                case '-':
                    new_num.at(i+1) = new_num.at(i) - new_num.at(i+1);
                    break;
                case '*':
                    new_num.at(i+1) = new_num.at(i) * new_num.at(i+1);
                    break;
            }
            new_num.erase(new_num.begin()+i);
            new_ops.erase(new_ops.begin()+i);
            generateResult(new_num,new_ops,result);
        }
        return;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.