首页 > 其他 > 详细

携程笔试1-排列问题

时间:2021-05-14 10:19:21      阅读:8      评论:0      收藏:0      [点我收藏+]

 

 

 

public class XieCheng2 {
    /**
     * 给定 n个岛屿的分数:  x1 x2.. xn
     * m张牌:  y1 y2.. ym
     * 每次前进 y1
     * 问最高分数
     */
    public static void main(String[] args) {
        int n=4, m=2;
        int[] scores = new int[]{1,2,3,4};

        int[] cards = new int[]{1,2};
        int maxScores=0;
        LinkedList<ArrayList<Integer>> allCards = getAll(cards);

        for (ArrayList<Integer> allCard : allCards) {
            int cIndex=0;
            int cScore=scores[0];
            for (int i = 0; i < allCard.size(); i++) {
                Integer cardNum = allCard.get(i);
                cIndex += cardNum;
                if(cIndex>n-1){
                    break;
                }
                cScore+=scores[cIndex];

            }
            maxScores = Math.max(cScore,maxScores);
        }
        System.out.println(maxScores);
    }
    public static LinkedList<ArrayList<Integer>> list = new LinkedList<>();
    public static LinkedList<ArrayList<Integer>> getAll(int[] a){
        boolean[] used = new boolean[a.length];
        Deque<Integer> deque = new ArrayDeque<>();

        for(int i=0; i<a.length; i++){
            deque.addLast(a[i]);
            used[i] = true;
            dfs(a.length,a,used,deque);
            used[i] = false;
            deque.removeLast();
        }
        return list;
    }

    private static void dfs(int n, int[] a, boolean[] used, Deque<Integer> deque) {
        if(deque.size() == n){
            list.add(new ArrayList<>(deque));
            return;
        }
        for(int i=0; i<a.length; i++){
            if(!used[i]){
                deque.addLast(a[i]);
                used[i] = true;
                dfs(a.length,a,used,deque);
                used[i] = false;
                deque.removeLast();
            }
        }
    }
}

 

携程笔试1-排列问题

原文:https://www.cnblogs.com/wsZzz1997/p/14766470.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!