力扣---2020.4.2

289. 生命游戏

class Solution {
    private static final int[] DX = {0,0,1,-1,1,1,-1,-1};
    private static final int[] DY = {1, -1, 0, 0, 1, -1, 1, -1};
    public void gameOfLife(int[][] board) {
        if(board.length==0){
            return;
        }
        int n = board.length,m = board[0].length;
        for(int i = 0;i<n;++i){
            for(int j = 0;j<m;++j){
                int cnt = 0;
                for(int k = 0;k<8;k++){
                    int x = i + DX[k];
                    int y = j + DY[k];
                    if(x<0||x>=n||y<0||y>=m){
                        continue;
                    }
                    // 这里不能直接加board[x][y],因为 board[x][y] 的倒数第二位是可能有值的。
                    cnt += board[x][y] & 1;
                }
                if ((board[i][j] & 1) > 0) {
                    // 这个是活细胞
                    if (cnt >= 2 && cnt <= 3) {
                        // 周围有2/3个活细胞,下一个状态还是活细胞。
                        board[i][j] = 0b11;
                    }
                    // 周围活细胞过多或过少都会死,因为原数据是0b01,所以这里不用额外赋值。
                } else if (cnt == 3) {
                    // 这个是死细胞,周围有3个活细胞,下一个状态变为活细胞。
                    board[i][j] = 0b10;
                }
            }
        }
        // 最后一位去掉,倒数第二位变为更新后的状态。
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < m; ++j) {
                board[i][j] >>= 1;
            }
        }
    }
}

面试题34. 二叉树中和为某一值的路径

//回溯
class Solution {
    LinkedList<List<Integer>> res = new LinkedList<>();
    LinkedList<Integer> path = new LinkedList<>(); 
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        recur(root, sum);
        return res;
    }
    void recur(TreeNode root, int tar) {
        if(root == null) return;
        path.add(root.val);
        tar -= root.val;
        if(tar == 0 && root.left == null && root.right == null)
            res.add(new LinkedList(path));
        recur(root.left, tar);
        recur(root.right, tar);
        path.removeLast();
    }
}

面试题10- II. 青蛙跳台阶问题

class Solution {
    public int numWays(int n) {
        int a = 1,b = 1;
        int sum;
        for(int i = 0;i<n;i++){
            sum = (a+b)%1000000007;
            a = b;
            b = sum;
        }
        return a;
    }
}
//取模之后,能够计算的数据更多
class Solution {
    public int numWays(int n) {
        if(n == 0||n == 1) return 1;
        if(n == 2) return 2;
        int[] dp = new int[2];
        dp[0] = 1;
        dp[1] = 2;
        for(int i=3;i<=n;i++){
            int tmp = (dp[1] + dp[0])%1000000007;;
            dp[0] = dp[1];
            dp[1] = tmp;
        }
        return dp[1];
    }
}

你知道的越多,你不知道的越多。
有道无术,术尚可求,有术无道,止于术。
如有其它问题,欢迎大家留言,我们一起讨论,一起学习,一起进步

你可能感兴趣的:(数据结构与算法)