每日一题:[LeetCode:剑指 Offer 46、12、26]

每日一题day1:LeetCode

剑指 Offer 46. 把数字翻译成字符串

剑指 Offer 12. 矩阵中的路径

剑指 Offer 26. 树的子结构


1、剑指 Offer 46. 把数字翻译成字符串

class Solution {
    
    
public:
    int translateNum(int num) {
    
    
        int a = 1, b = 1, ans;
        string s = to_string(num);
        int size = s.size();
        if(size == 1) ans = 1;
        else{
    
    
            for(int i = 1; i < size; i++){
    
    
                string temp = s.substr(i - 1, 2);
                int k = stoi(temp);
                if(k >= 10 && k <= 25) ans = a + b;
                a = b; b = ans;
            }
        }
        return ans;
    }
};

2、剑指 Offer 12. 矩阵中的路径

class Solution {
    
    
public:
    int n, m;
    bool vis[205][205], ok = false;
    int dir[4][2] = {
    
    {
    
    -1, 0}, {
    
    1, 0}, {
    
    0, -1}, {
    
    0, 1}};
    bool check(int x, int y){
    
    
        if(x < 0 || x >= n || y < 0 || y >= m) return false;
        if(vis[x][y]) return false;
        return  true;
    }
    void dfs(vector<vector<char>>& board, string word, int x, int y, int pos){
    
    
        if(pos == word.size() - 1){
    
    
            ok = true;
            return ;
        }
        for(int i = 0; i < 4; i++){
    
    
            int X = x + dir[i][0];
            int Y = y + dir[i][1];
            if(check(X, Y) && word[pos + 1] == board[X][Y] && !ok){
    
    
                vis[X][Y] = true;
                dfs(board, word, X, Y, pos + 1);
                vis[X][Y] = false;
            }
        }
    }
    bool exist(vector<vector<char>>& board, string word) {
    
    
        m = board[0].size(), n = board.size();
        for(int i = 0; i < n; i++){
    
    
            for(int j = 0; j < m; j++){
    
    
                if(board[i][j] == word[0]){
    
    
                    vis[i][j] = true;
                    dfs(board, word, i, j, 0);
                    vis[i][j] = false;
                    if(ok) return true;
                }
            }
        }
        return false;
    }
};

3、剑指 Offer 26. 树的子结构

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    bool dfs(TreeNode* A, TreeNode* B){
    
    
        if(B == NULL) return true;
        if(A == NULL) return false;
        return A -> val == B -> val && dfs(A -> left, B -> left) && dfs(A -> right, B -> right);
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
    
    
        if(A == NULL || B == NULL) return false;
        return dfs(A, B) || isSubStructure(A -> left, B) || isSubStructure(A -> right, B);
    }
};

2021/2/28完结。

猜你喜欢

转载自blog.csdn.net/shangzhengyu/article/details/114219949