lintcode(653)Add Operators

本文介绍了一种使用深度优先搜索(DFS)算法解决特定问题的方法:给定一个仅包含0-9数字的字符串及目标值,寻找所有可能的运算符(+、-、*)组合方式,使得该字符串通过这些运算符连接后的计算结果等于目标值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description:

Given a string that contains only digits 0-9 and a target value, return all possibilities to add binary operators (not unary) +-, or * between the digits so they evaluate to the target value.

Explanation:

"123", 6 -> ["1+2+3", "1*2*3"] 
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []

Solution:

DFS(Depth-first-search).

找出所有可能的情况,涉及到多种组合方式,对每一条分支(组合方式)都要进行深度搜索,直至不能深入,所以采用深度优先搜索。

首先建立一个list来存储结果。建立dfs函数来搜索所有情况。搜索过程中先截取字符串,作为当前操作的数值,然后分别匹配+ - * 三种运算,要注意计算的优先级,所以计算乘法时,要回溯。其次要注意特殊情况,0可以单独作为操作数,但是不可以在多位数中占首位;第一次计算时,当前表达式为空,前边不添加计算符。

public class Solution {
    /**
     * @param num a string contains only digits 0-9
     * @param target an integer
     * @return return all possibilities
     * Author:Sunday0904
     */
    
    ArrayList<String> result = new ArrayList<String>();
    
    public List<String> addOperators(String num, int target) {
        // Write your code here
        DFS(num , target , "" , 0 , 0);
        return result;
    }
    
    public void DFS(String num , int target , String temp , long curResult , long preNum){
        
        if(curResult == target && num.length() == 0){
            String expression = new String(temp);
            result.add(expression);
            return ;
        }
        
        for(int i = 1;i<=num.length();i++){
            String curStr = num.substring(0 , i);
            
            if(curStr.length() > 1 && curStr.startsWith("0")){
                return ;
            }
            
            String newNum = num.substring(i);
            long curNum = Long.parseLong(curStr);
            
            if(temp.length() == 0){
                DFS(newNum , target , curStr , curNum , curNum);
            }else{
                DFS(newNum , target , temp + "+" + curStr , curResult + curNum , curNum);
                DFS(newNum , target , temp + "-" + curStr , curResult - curNum , -curNum);
                DFS(newNum , target , temp + "*" + curStr , curResult - preNum + preNum * curNum , preNum * curNum);
            }
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值