携程笔试1-排列问题

 

 

 

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();
            }
        }
    }
}

 

上一篇:R语言—数据的调整与处理


下一篇:【java】剑指offer59-II_队列的最大值