Simple and straight forward Ruby solution


  • 0
    T

    uncomment the line for 'puts' to see the output per recursion.

    def add_operators(num, target)
        @sets = []
        @num = num
        @target = target
        add_forward("", nil, nil, 0)
        @sets
    end
    
    def add_forward(expression_str, expression_val, mult, counter)
        #puts "counter: #{counter}, expression_str: #{expression_str}, #{eval(expression_str)}"
        if counter == @num.length && expression_val == @target
            @sets << expression_str
            return
        end
        size = @num[counter] == "0" ? counter + 1 : @num.length
        for i in (counter+1)..size
            current_num = @num[counter...i].to_i
            if expression_str == ""
                add_forward(current_num.to_s, current_num, current_num, i)
                next
            end
    
            add_forward(expression_str+"+"+current_num.to_s, expression_val+current_num, current_num, i)
            add_forward(expression_str+"-"+current_num.to_s, expression_val-current_num, -current_num, i)
            add_forward(expression_str+"*"+current_num.to_s, (expression_val-mult)+(mult*current_num), (mult*current_num), i)
        end
    end
    

Log in to reply
 

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