题解 | 田忌赛马

田忌赛马

https://www.nowcoder.com/practice/49d799f65a0749588e9cd7e6135a4a9a

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] arr1 = new int[3];
        int[] arr2 = new int[3];
        for(int i = 0;i<3;i++){
            arr1[i] = in.nextInt();
        }
        for(int i = 0;i<3;i++){
            arr2[i] = in.nextInt();
        }
        List<List<Integer>> list = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] used = new boolean[3];
        backtrack(arr2,path,used,list);
        boolean result = false;
        for(List<Integer> l : list){
            int count = 0;
            for(int i =0;i<3;i++){
                if(l.get(i)>arr1[i]) count++;
            }
            if(count>=2) {
                result = true;
                break;
            }
        }
        if(result)
            System.out.println("Yes");
        else    System.out.println("No");
    }
    public static void backtrack(int[] nums, List<Integer> path,boolean[] used,        List<List<Integer>> list){
        if(path.size()==nums.length){
            list.add(new ArrayList<>(path));
            return;
        }
        for(int i = 0;i<nums.length;i++){
            if(used[i]==true) continue; 
            used[i] = true;
            path.add(nums[i]);
            backtrack(nums,path,used,list);
            path.remove(path.size()-1);
            used[i]=false;
        }
    }
}

全部评论

相关推荐

12-01 14:24
吉首大学 Java
点赞 评论 收藏
分享
未知的命运:大佬这都找不到我还找啥啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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