C# solution


  • 0
    S
    public class Solution {
        public IList<int> DiffWaysToCompute(string input) 
        {
            var result = new List<int>();
            if(string.IsNullOrEmpty(input))
                return result;
            return Helper(input,  new Dictionary<string, List<int>>());
        }
        
        private List<int> Helper(string input, Dictionary<string, List<int>> dic)
        {
            if(dic.ContainsKey(input))
                return dic[input];
            var result = new List<int>();
            int num;
            if(int.TryParse(input, out num))
            {
                result.Add(num);
            }
            else
            {
                for(int i =0 ; i<input.Length; i++)
                {
                    if(new List<char>{'+', '-', '*', '/'}.Contains(input[i]))
                    {
                        var left = Helper(input.Substring(0, i), dic);
                        var right = Helper(input.Substring(i+1), dic);
                        foreach(var l in left)
                        foreach(var r in right)
                        {
                            var n = Cal(l, r, input[i]);
                            result.Add(n);
                        }
                    }
                }
            }
            dic[input] = result;
            return result;
        }
        
        private int Cal(int left, int right, char op)
        {
            switch(op)
            {
                case '+':
                    return left+right;
                case '-':
                    return left-right;
                case '*':
                    return left*right;
                case '/':
                    return left/right;
            }
            return 0;
        }
    }
    

Log in to reply
 

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