代码随想录算法训练营第三十天| 332. 重新安排行程、51. N 皇后、37. 解数独

[LeetCode] 332. 重新安排行程

[LeetCode] 332. 重新安排行程 文章解释

[LeetCode] 332. 重新安排行程 视频解释

题目:

给你一份航线列表 tickets ,其中 tickets[i] = [fromi, toi] 表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。

所有这些机票都属于一个从 JFK(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK 开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。

  • 例如,行程 ["JFK", "LGA"]["JFK", "LGB"] 相比就更小,排序更靠前。

假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。

示例 1:

输入:tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
输出:["JFK","MUC","LHR","SFO","SJC"]

示例 2:

输入:tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
输出:["JFK","ATL","JFK","SFO","ATL","SFO"]
解释:另一种有效的行程是 ["JFK","SFO","ATL","JFK","ATL","SFO"] ,但是它字典排序更大更靠后。

提示:

  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • fromi.length == 3
  • toi.length == 3
  • fromitoi 由大写英文字母组成
  • fromi != toi

[LeetCode] 332. 重新安排行程

自己看到题目的第一想法

    穷举所有的组合, 当出现新的组合时, 和上一个组合对比一下, 如果发现是更小值的路径, 则更新对应的数据.

    test case ok, 提交超时~

看完代码随想录之后的想法

    用 Map 来优化确实优雅了很多, 不需要穷举了.

// test case 可以过, 但是超时了...
class Solution {
    private LinkedList<String> path = new LinkedList<>();
    public List<String> findItinerary(List<List<String>> tickets) {
        // 升序排列
        Collections.sort(tickets, new Comparator<List<String>>() {
            @Override
            public int compare(List<String> t0, List<String> t1) {
                return t0.get(1).compareTo(t1.get(1));
            }
        });
        path.add("JFK");
        backTracking(tickets, new boolean[tickets.size()]);
        return path;
    }
    private boolean backTracking(List<List<String>> tickets, boolean[] used) {
        if (path.size() == tickets.size() + 1) {
            return true;
        }
        for (int i = 0; i < tickets.size(); i++) {
            if (used[i] || !tickets.get(i).get(0).equals(path.getLast())) {
                continue;
            }
            path.add(tickets.get(i).get(1));
            used[i] = true;
            if (backTracking(tickets, used)) {
                return true;
            }
            path.removeLast();
            used[i] = false;
        }
        return false;
    }
}
// 效率不高, 但是 AC 了... 不深究
class Solution {
    private LinkedList<String> path = new LinkedList<>();
    private Map<String, TreeMap<String, Integer>> tickets = new HashMap<>();
    public List<String> findItinerary(List<List<String>> tickets) {
        for (int i = 0; i < tickets.size(); i++) {
            String fromAirPort = tickets.get(i).get(0);
            TreeMap<String, Integer> destinations = this.tickets.get(fromAirPort);
            if (destinations == null) {
                destinations = new TreeMap<>();
                this.tickets.put(fromAirPort, destinations);
            }
            String toAirPort = tickets.get(i).get(1);
            destinations.put(toAirPort, destinations.getOrDefault(toAirPort, 0) + 1);
        }
        path.add("JFK");
        backTracking(tickets.size() + 1);
        return path;
    }
    private boolean backTracking(int pathNumber) {
        if (path.size() == pathNumber) {
            return true;
        }
        Map<String, Integer> destinations = tickets.get(path.getLast());
        if (destinations == null) {
            return false;
        }
        for (Map.Entry<String, Integer> entry : destinations.entrySet()) {
            if (entry.getValue() == 0) {
                continue;
            }
            path.add(entry.getKey());
            entry.setValue(entry.getValue() - 1);
            if (backTracking(pathNumber)) {
                return true;
            }
            path.removeLast();
            entry.setValue(entry.getValue() + 1);
        }
        return false;
    }
}

自己实现过程中遇到哪些困难 

    审题的时候没有注意到会出现多个 A-》B 这样的组合, 也没注意到所有的输入数据中, 每一条数据都一定存在一条能把所有机票用完的路径... 导致自己想的时候很懵. 感觉 LeetCode 对于题目的描述还是稍微粗糙了一些, 对比起来官方题解就严谨很多.

    自己实现的时候没有想到排序这个机制的做法, 感觉真的是有点弱, 这么本能的想法怎么会完全没有想到呢, 只想到暴力求解了.

[LeetCode] 51. N 皇后

[LeetCode] 51. N 皇后 文章解释

[LeetCode] 51. N 皇后 视频解释

[LeetCode] 51. N 皇后

自己看到题目的第一想法

    对于每一层, 遍历所有的位置, 放入皇后. 每放入一个皇后时, 就再往下一层递归. 直到所有放入的皇后, 检查合法性都通过, 则完成任务.

看完代码随想录之后的想法

    基本差不多, 这一题是比较简单的. (怎么判断难易度: 看视频的长度就可以大概猜到~)

// 效率极低...
class Solution {
    private List<List<String>> result = new ArrayList<>();
    private List<StringBuilder> chessBoard = new ArrayList<>();
    public List<List<String>> solveNQueens(int n) {
        for (int i = 0; i < n; i++) {
            StringBuilder strBuilder = new StringBuilder();
            for (int j = 0; j < n; j++) {
                strBuilder.append('.');
            }
            chessBoard.add(strBuilder);
        }
        backTracking(0);
        return result;
    }
    private void backTracking(int row) {
        if (row == chessBoard.size()) {
            List<String> path = new ArrayList<>();
            for (int i = 0; i < chessBoard.size(); i++) {
                path.add(chessBoard.get(i).toString());
            }
            result.add(path);
            return;
        }
        for (int i = 0; i < chessBoard.size(); i++) {
            if (!isValid(row, i)) {
                continue;
            }
            chessBoard.get(row).setCharAt(i, 'Q');
            backTracking(row + 1);
            chessBoard.get(row).setCharAt(i, '.');
        }
    }
    private boolean isValid(int row, int column) {
        for (int i = row; i >= 0; i--) {
            if (chessBoard.get(i).charAt(column) == 'Q') {
                return false;
            }
        }
        for (int i = row, j = column; i >= 0 && j >= 0; i--, j--) {
            if (chessBoard.get(i).charAt(j) == 'Q') {
                return false;
            }
        }
        for (int i = row, j = column; i >= 0 && j < chessBoard.size(); i--, j++) {
            if (chessBoard.get(i).charAt(j) == 'Q') {
                return false;
            }
        }
        return true;
    }
}

自己实现过程中遇到哪些困难 

    无

[LeetCode] 37. 解数独

[LeetCode] 37. 解数独 文章解释

[LeetCode] 37. 解数独 视频解释

题目:

写一个程序,通过填充空格来解决数独问题。

数独的解法需 遵循如下规则

  1. 数字 1-9 在每一行只能出现一次。
  2. 数字 1-9 在每一列只能出现一次。
  3. 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)

数独部分空格内已填入了数字,空白格用 '.' 表示。

示例 1:

输入:board = [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]]
输出:[["5","3","4","6","7","8","9","1","2"],["6","7","2","1","9","5","3","4","8"],["1","9","8","3","4","2","5","6","7"],["8","5","9","7","6","1","4","2","3"],["4","2","6","8","5","3","7","9","1"],["7","1","3","9","2","4","8","5","6"],["9","6","1","5","3","7","2","8","4"],["2","8","7","4","1","9","6","3","5"],["3","4","5","2","8","6","1","7","9"]]

提示:

  • board.length == 9
  • board[i].length == 9
  • board[i][j] 是一位数字或者 '.'
  • 题目数据 保证 输入数独仅有一个解

[LeetCode] 37. 解数独

自己看到题目的第一想法

    继续暴力破解吧.

    为啥写不出来捏...

看完代码随想录之后的想法

    哦哈... 那么简单! 我会!!!

    怎么又写不出来了....

// 效率一般
class Solution {
    public void solveSudoku(char[][] board) {
        backTracking(board, 0, 0);
    }
    private boolean backTracking(char[][] board, int row, int column) {
        // 从左往右从上往下, 挑选出第一个没有填上数字的位置
        for (; row < board.length; row++) {
            int j = 0;
            for (j = column; j < board[row].length; j++) {
                if (board[row][j] == '.') {
                    column = j;
                    break;
                }
            }
            if (j == board[row].length) {
                column = 0;
            } else {
                break;
            }
        }
        // 所有元素都放入了合理的数字, 递归成功
        if (row == board.length) {
            return true;
        }
        // 将 1 ~ 9 中的数字, 放入当前位置, 并递归下一个数字
        for (char i = '1'; i <= '9'; i++) {
            // 检查一下当前位置是否能放入当前的数字
            if (!isValid(board, row, column, i)) {
                continue;
            }
            board[row][column] = i;// 放入当前的数字
            if (backTracking(board, row, column)) {
                return true;
            }
            board[row][column] = '.';// 删除当前的数字, 进行下一次递归
        }
        return false;
    }
    private boolean isValid(char[][] board, int row, int column, int number) {
        for (int i = 0; i < board.length; i++) {
            if (board[row][i] == number || board[i][column] == number) {
                return false;
            }
        }
        int rowStart = (row/3)*3;
        int columnStart = (column/3)*3;
        for (int i = rowStart; i < rowStart + 3; i++) {
            for (int j = columnStart; j < columnStart + 3; j++) {
                if (board[i][j] == number) {
                    return false;
                }
            }
        }
        return true;
    }
}

自己实现过程中遇到哪些困难 

    递归的结束条件写的不好.

   

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值