题解 | #24点运算#

24点运算

https://www.nowcoder.com/practice/7e124483271e4c979a82eb2956544f9d

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    private static Map<String,Integer> map = new HashMap<String,Integer>(){
        {put("2",2);put("3",3);put("4",4);put("5",5);put("6",6);put("7",7);
        put("8",8);put("9",9);put("10",10);put("J",11);put("Q",12);put("K",13);
        put("A",1);}
    };

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        if(str.toLowerCase().contains("joker")){
            System.out.println("ERROR");
        }else{
            //注意这里exp传参不是引用传参,无法得到返回的值
            if(!dfs(str.split(" "),0,"",0)){
                System.out.println("NONE");
            }
        }
        
    }

    public static boolean dfs(String[] num,int res,String exp,int pos){
        //这里的循环可以保证每个字符都能在相同位置出现
        for(int i = 0;i<num.length;i++){
            if(!"".equals(num[i])){
                String tempStr = num[i];
                num[i] = "";//置为空表示已遍历

                int val = map.get(tempStr);
                if(pos == 0){
                    if(dfs(num,val,tempStr,pos+1)){
                        return true;
                    }
                }else{
                    if(dfs(num,res+val,exp+"+"+tempStr,pos+1)||
                    dfs(num,res-val,exp+"-"+tempStr,pos+1)||
                    dfs(num,res*val,exp+"*"+tempStr,pos+1)||
                    dfs(num,res/val,exp+"/"+tempStr,pos+1)){
                        return true;
                    }
                    
                }
                num[i] = tempStr;//还原
            }
        }
        if(res == 24 && pos == num.length){
            System.out.println(exp);
            return true;
        }
        return false;
    }
}

需要深刻理解DFS(Depth First Search深度优先算法),

注意最后判断是否等于24还需要判断是否四个字符都已使用过

 if(res == 24 && pos == num.length){
   System.out.println(exp);
   return true;
 }

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务