zoukankan      html  css  js  c++  java
  • (递归) leetcode 779. Kth Symbol in Grammar, 542. 01 Matrix

    题意:N表示行数,K表示第N行第几个数,它们都从1开始计数。其中若上一行中有0,则在下一行变为01;1变为10。最后输出给定第N行第K个数的值。

    思路:用递归来做,可以表示为一个二叉树,第N行第K个数的父亲结点的位置是第N-1行第(K+1)/2个数。观察规律可以看出:偶数结点等于它的父结点;奇数结点等于它的父结点取反。因为0 -> 01 , 1 -> 10

                0
         /            
        0               1
      /             /     
     0     1        1       0
    /     /      /      / 
    0  1  1   0   1   0   0   1
    class Solution {
    public:
        int kthGrammar(int N, int K) {
            if(N==1)
                return 0;
            else 
                return (K%2 == 0)? !kthGrammar(N-1, (K+1)/2): kthGrammar(N-1, (K+1)/2);
        }
    };

     思路:(K+1)/2 表示K的父结点,当K是偶数时,K&1 的值为 0,0^1的值为1,1与任何值做异或都相当于将这个值取反,所以意味着将父结点的值取反;K是奇数时,K&1 的值为1,1^1的值为0,0与任何值做异或都相当于这个值,所以意味着将继承父结点的值 。

    class Solution {
    public:
        int kthGrammar(int N, int K) {
            if(N==1)
                return 0;
            else 
                return kthGrammar(N-1, (K+1)/2) ^ (K&1) ^ 1;  
        }
    };

    递归+BFS:将matrix矩阵中0值都push进队列q中,然后将相应的res置为0,(res初始值为-1),然后遍历队列q中的元素,当满足条件时,改变相应的res同时将该点入队。

    class Solution {
    public:
        vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
            int move[4][2] = {{0,1}, {0,-1}, {1,0}, {-1,0}};
            int n = matrix.size(), m = matrix[0].size();
            vector<vector<int>> res(n, vector<int>(m, -1));
            queue<pair<int, int>> q;
            for(int i=0; i<n; ++i){
                for(int j=0; j<m; ++j){
                    if(matrix[i][j] == 0){
                        res[i][j] = 0; 
                        q.push(make_pair(i,j));
                    }
                }
            }
            while(!q.empty()){
                pair<int, int> now = q.front();
                q.pop();
                for(int i=0; i<4; ++i){
                    //bfs
                    int x = now.first + move[i][0];
                    int y = now.second + move[i][1];
                    if(x<0 || x>=n || y<0 || y>=m || res[x][y]!=-1)
                        continue;
                    res[x][y] = res[now.first][now.second] +1;
                    q.push(make_pair(x,y));
                }
            }
            return res;
        }
    };
  • 相关阅读:
    Java tomcat max-http-header-size配置导致的oom
    Idea修改jvm参数
    Java List的SubList使用问题
    Java Arrays.asList的三个坑
    Java 重写equals的时候为什么一定要重写hashcode-一个例子
    远心镜头
    镜头常识总结
    halcon中保存图像jpeg的压缩比
    红外光 相机拍照
    电磁波的穿透能力总结
  • 原文地址:https://www.cnblogs.com/Bella2017/p/11197186.html
Copyright © 2011-2022 走看看