Arithmetic Expressions

  • + 0 comments

    Simplest Solution I have Seen So far:-

    Code

    class Result {
    
    public static String ans="";
    
    public static boolean Solve(List<Integer>arr,int prev,String cur,int idx,boolean map[]  []){
            prev=prev%101;
    
     if(idx==arr.size()){
            if(prev%101==0){
                     ans=cur;
                        return true;  
                 }
    return false;
    }
    
     //Checking if at this index Previsiously we Got this remainder(prev)
    
    if(map[idx][prev+101])return false;
    map[idx][prev+101]=true;
    
        //recursion   
    
        if(Solve(arr,prev+arr.get(idx)%101,cur+"+"+arr.get(idx),idx+1,map))return true;
        if(Solve(arr,prev-arr.get(idx)%101,cur+"-"+arr.get(idx),idx+1,map))return true;
        if(Solve(arr,prev*arr.get(idx)%101,cur+"*"+arr.get(idx),idx+1,map))return true;
    
       return false;
    }
    
    public static String arithmeticExpressions(List<Integer> arr){
    
    boolean[][]map=new boolean[arr.size()][2*101];
    
    Solve(arr,arr.get(0),""+arr.get(0),1,map);
    
     return ans;
    }
    

    }