thảo luận Leetcode mỗi ngày

Java:
class Solution {
    public String smallestFromLeaf(TreeNode root) {
        return smallestFromLeaf(root, new StringBuilder()).toString();
    }
    private StringBuilder smallestFromLeaf(TreeNode node,StringBuilder sb){
        if(node==null) return sb;
        sb.insert(0, (char) ('a' + node.val));
        StringBuilder sbLeft = smallestFromLeaf(node.left, new StringBuilder(sb));
        StringBuilder sbRight = smallestFromLeaf(node.right, new StringBuilder(sb));
        if(node.left==null){
            return sbRight;
        }
        else if(node.right==null){
            return sbLeft;
        }
        return sbLeft.compareTo(sbRight)<=0?sbLeft:sbRight;
    }
}
 
Java:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    String smallestString = "";

    public String smallestFromLeaf(TreeNode root) {
        dfs(root, "");
        return smallestString;
    }

    private void dfs(TreeNode root, String currentString) {
        if (root == null) {
            return;
        }
        currentString = (char) (root.val + 'a') + currentString;
        if (root.left == null && root.right == null) {
            smallestString = smallestString.isEmpty() || smallestString.compareTo(currentString) > 0 ? currentString : smallestString;
        }
        if (root.left != null) {
            dfs(root.left, currentString);
        }
        if (root.right != null) {
            dfs(root.right, currentString);
        }
    }
}
 
Java:
class Solution {
    public String smallestFromLeaf(TreeNode root) {
        return travel(root, "");
    }
    public String travel(TreeNode root, String str){
        if(root == null) return "";
        str = new Character((char)(97 + root.val)).toString() + str;
        if(root.left == null && root.right == null){
            return str;
        }
        String left = travel(root.left, str);
        String right = travel(root.right, str);
        if((left == "" || left.compareTo(right) > 0) && right != ""){
            return right;
        }
        return left;
    }
}
 
Java:
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    StringBuilder sb = new StringBuilder();
    String best = "~";
    public String smallestFromLeaf(TreeNode root) {
        sb.insert(0, (char) ('a' + root.val));
        if (root.left == null && root.right == null) {
            String curr = sb.toString();
            if (curr.compareTo(best) < 0) {
                best = curr;
            }
        }
        
        if (root.left != null)
            smallestFromLeaf(root.left);
        if (root.right != null)
            smallestFromLeaf(root.right);
        
        sb.deleteCharAt(0);

        return best;
    }
}
 
Code:
var smallestFromLeaf = function(root) {
    let smallest;
    function dfs(node, path) {
        path = String.fromCharCode(node.val + 97) + path;

        if (!node.left && !node.right) {
            if (!smallest || path < smallest) {
                smallest = path;
            }
        }

        if (node.left) dfs(node.left, path);
        if (node.right) dfs(node.right, path);
    }

    dfs(root, '');

    return smallest;
};
 
Thử dùng stack mà code ko chạy, đành dùng recursive
1xK3bm3.png

Code:
    private String ans = null;

    /**
     * Time: O(nh) where h = path = height of tree
     * Space O(h)
     */
    void dfs(TreeNode root, StringBuilder sb) {
        if (root == null) return;

        sb.append((char) (root.val + 'a'));

        if (root.left == null && root.right == null) {
            final String path = sb.reverse().toString();
            sb.reverse(); // rollback;
            if (ans == null || ans.compareTo(path) > 0)
                ans = path;
        }

        dfs(root.left, sb);
        dfs(root.right, sb);

        sb.deleteCharAt(sb.length() - 1);
    }

    /**
     * Traversal over the tree node
     */
    public String smallestFromLeaf(TreeNode root) {
        dfs(root, new StringBuilder());
        return ans;
    }
 
Code:
class Solution {
    String res = "";
    public String smallestFromLeaf(TreeNode root) {
        DFS(root, "");
        return res;
    }

    private void DFS(TreeNode node, String sb) {
        if(node == null) return;
       
        sb = (char)(node.val + 'a') + sb;
        if(node.left == null && node.right == null) {
            if(res.length() == 0 || res.compareTo(sb) > 0) {
                res = sb;
            }
        }
        if(node.left != null) DFS(node.left, sb);
        if(node.right != null) DFS(node.right, sb);
    }
}
Đoạn implement BFS này phải check editor :too_sad:
Code:
class Solution {
    public String smallestFromLeaf(TreeNode root) {
        Queue<Pair<TreeNode, String>> queue = new LinkedList();
        queue.add(new Pair<TreeNode, String>(root, String.valueOf((char)(root.val+'a'))));
        String res = "";
        while(!queue.isEmpty()) {
            Pair<TreeNode, String> curr = queue.poll();
            TreeNode currNode = curr.getKey();
            String s = curr.getValue();
           
            if(currNode.left == null && currNode.right == null) {
                if(res.isEmpty()) res = s;
                res = s.compareTo(res) < 0 ? s : res;
            }
            if(currNode.left != null) queue.add(new Pair<>(currNode.left, (char) (currNode.left.val + 'a') + s));
            if(currNode.right != null) queue.add(new Pair<>(currNode.right, (char) (currNode.right.val + 'a') + s));
        }
        return res;
    }
}
 
C++:
class Solution {
public:
    void dfs(TreeNode* root, string s, string& res) {
        s += 'a' + root->val;
        if (!root->left && !root->right) {
            string ss(s);
            reverse(ss.begin(), ss.end());
            if (res == "" || ss < res)
                res = ss;
        }
        if (root->left)
            dfs(root->left, s, res);
        if (root->right)
            dfs(root->right, s, res);
    }
    string smallestFromLeaf(TreeNode* root) {
        string res;
        dfs(root, "", res);
        return res;
    }
};
 
Bài đăng 1 cụ (già) trên leetcode
I realized that I was doing Leetcode wrong at the beginning. I did not come to Leetcode to prepare for interviews. I’m too old to start a career at the FAANG companies to be honest. No, I love puzzles and in the beginning I thought I was testing my programming IQ. I was wrong of course. I spent hours if not days on some problems and I was not able to solve them. Even after looking at someone else's code, I could not understand how it worked…

That’s because like many who start here, I was doing Leetcode the wrong way. You’re not supposed to find the algorithms by yourself. Of course, there is a lot of satisfaction in finding one by yourself, but unless you’re a true genius, you're not going to find what the Dijkstra, Bellman, and so on found with their brilliant intellect.

No, the good way to use Leetcode is to use it to learn. If you don’t find the solution to a problem relatively quickly, say one hour, stop there. Read the solution, understand it and try to reproduce it. Even if you’re into competitive programming, that's the way to do it: you learn the patterns and then you apply them wherever it fits. Read also the many variations of solutions and learn from the best.

Also try to explain your solutions (that’s part of the Feynman method “Teach it to yourself or someone else. …”. If you can’t explain it clearly it means that you still have not completely absorbed.the concept.

And don’t be impatient. If you cannot grasp Dynamic Programming in 2 days or even one week, don’t worry, many people got there. Persist, and at some point it will click. Practice, practice and practice. You’re not a genius, but you’re not stupid. Let yourself have the time to learn.

Don’t compare yourself to others. You will see comments like “This Medium question should be labeled Easy” and then you despair because even easy questions feel hard for you. The thing is once you have learned something it becomes easy. If you try to compare to others you are comparing apples to oranges. Different people at different stages of their development will never experience the same level of difficulty. So ignore these comments and focus on your own progress. Compare yourself to where you were a few months ago and appreciate the progress you made.

Happy leetcoding to all.
 
Bài đăng 1 cụ (già) trên leetcode
I realized that I was doing Leetcode wrong at the beginning. I did not come to Leetcode to prepare for interviews. I’m too old to start a career at the FAANG companies to be honest. No, I love puzzles and in the beginning I thought I was testing my programming IQ. I was wrong of course. I spent hours if not days on some problems and I was not able to solve them. Even after looking at someone else's code, I could not understand how it worked…

That’s because like many who start here, I was doing Leetcode the wrong way. You’re not supposed to find the algorithms by yourself. Of course, there is a lot of satisfaction in finding one by yourself, but unless you’re a true genius, you're not going to find what the Dijkstra, Bellman, and so on found with their brilliant intellect.

No, the good way to use Leetcode is to use it to learn. If you don’t find the solution to a problem relatively quickly, say one hour, stop there. Read the solution, understand it and try to reproduce it. Even if you’re into competitive programming, that's the way to do it: you learn the patterns and then you apply them wherever it fits. Read also the many variations of solutions and learn from the best.

Also try to explain your solutions (that’s part of the Feynman method “Teach it to yourself or someone else. …”. If you can’t explain it clearly it means that you still have not completely absorbed.the concept.

And don’t be impatient. If you cannot grasp Dynamic Programming in 2 days or even one week, don’t worry, many people got there. Persist, and at some point it will click. Practice, practice and practice. You’re not a genius, but you’re not stupid. Let yourself have the time to learn.

Don’t compare yourself to others. You will see comments like “This Medium question should be labeled Easy” and then you despair because even easy questions feel hard for you. The thing is once you have learned something it becomes easy. If you try to compare to others you are comparing apples to oranges. Different people at different stages of their development will never experience the same level of difficulty. So ignore these comments and focus on your own progress. Compare yourself to where you were a few months ago and appreciate the progress you made.

Happy leetcoding to all.
làm leetcode vì cảm giác accepted 1 bài lạ nó cũng vui
RKfPCqW.png
tham gia contest kiếm cái áo bước ra đường ae kính nể.:confident:
 
C#:
public class Solution
{
    public int IslandPerimeter(int[][] grid)
    {
        int result = 0;
        int rows = grid.Length;
        int cols = grid[0].Length;

        for (int row = 0; row < rows; row++)
        {
            for (int col = 0; col < cols; col++)
            {
                if (grid[row][col] == 0)
                {
                    continue;
                }
                result += 4;
                if (0 < row && grid[row -1][col] == 1)
                {
                    result--;
                }
                if (row < rows - 1 && grid[row + 1][col] == 1)
                {
                    result--;
                }
                if (0 < col && grid[row][col - 1] == 1)
                {
                    result--;
                }
                if (col < cols - 1 && grid[row][col + 1] == 1)
                {
                    result--;
                }
            }
        }

        return result;
    }
}
 
Back
Top