C# solution


  • 0
    T
    public class Solution {
        public IList<string> AddOperators(string num, int target) {
            var result = new List<string>();
            Helper(num,target,'+',0,"",result,0,num.Length,0);
            return result;
        }
        
        private void Helper(string num,int target,char prevOperator,
                            long prevNum,string r,List<string> result,
                           int index,int len,long current){
            long n = 0;
            for(int i = index;i<len;i++){
                if(i > index && num[index] == '0')
                    break;
                n = n * 10 + (num[i]-'0');
                
                long nextCurrent = 0;
                long nextNum = 0;
                
                if(prevOperator == '+'){
                    nextCurrent = current + n;
                    nextNum = n;
                }else if(prevOperator == '-'){
                    nextCurrent = current - n;
                    nextNum = -n;
                }else if(prevOperator == '*'){
                    nextCurrent = current - prevNum + prevNum * n;
                    nextNum = prevNum * n;
                }
                
                var nextR = r+prevOperator+n;
                if(i+1 >= len){
                    if(nextCurrent == target)
                        result.Add(nextR.Substring(1));
                    break;
                }
                
                Helper(num,target,'+',nextNum,nextR,result,i+1,len,nextCurrent);
                Helper(num,target,'-',nextNum,nextR,result,i+1,len,nextCurrent);
                Helper(num,target,'*',nextNum,nextR,result,i+1,len,nextCurrent);
            }
            
        }
    }
    

Log in to reply
 

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