Tuesday, September 8, 2020

LeetCode [489] Robot Room Cleaner

 489. Robot Room Cleaner

Hard

Given a robot cleaner in a room modeled as a grid.

Each cell in the grid can be empty or blocked.

The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees.

When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell.

Design an algorithm to clean the entire room using only the 4 given APIs shown below.

interface Robot {
  // returns true if next cell is open and robot moves into the cell.
  // returns false if next cell is obstacle and robot stays on the current cell.
  boolean move();

  // Robot will stay on the same cell after calling turnLeft/turnRight.
  // Each turn will be 90 degrees.
  void turnLeft();
  void turnRight();

  // Clean the current cell.
  void clean();
}

Example:

Input:
room = [
  [1,1,1,1,1,0,1,1],
  [1,1,1,1,1,0,1,1],
  [1,0,1,1,1,1,1,1],
  [0,0,0,1,0,0,0,0],
  [1,1,1,1,1,1,1,1]
],
row = 1,
col = 3

Explanation:
All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.

Notes:

  1. The input is only given to initialize the room and the robot's position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the mentioned 4 APIs, without knowing the room layout and the initial robot's position.
  2. The robot's initial position will always be in an accessible cell.
  3. The initial direction of the robot will be facing up.
  4. All accessible cells are connected, which means the all cells marked as 1 will be accessible by the robot.
  5. Assume all four edges of the grid are all surrounded by wall.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/**
 * // This is the robot's control interface.
 * // You should not implement it, or speculate about its implementation
 * interface Robot {
 *     // Returns true if the cell in front is open and robot moves into the cell.
 *     // Returns false if the cell in front is blocked and robot stays in the current cell.
 *     public boolean move();
 *
 *     // Robot will stay in the same cell after calling turnLeft/turnRight.
 *     // Each turn will be 90 degrees.
 *     public void turnLeft();
 *     public void turnRight();
 *
 *     // Clean the current cell.
 *     public void clean();
 * }
 */

class Solution {
    Set<String> visited;
    public void cleanRoom(Robot robot) {
        visited = new HashSet<>();
        helper(0,0,robot,0);
    }
    
    void helper(int i, int j, Robot robot, int dir){
        String key = i+":"+j;
        if(visited.contains(key)) return;
        
        robot.clean();
        visited.add(key);
        
        for(int k=0; k<4; ++k){
            int x = i, y = j;
            if(robot.move()){
                if(dir == 0) x--;
                else if(dir == 90) y++;
                else if(dir == 180) x++;
                else if(dir == 270) y--;
                helper(x, y, robot, dir);
                
                robot.turnRight();
                robot.turnRight();
                robot.move();
                robot.turnRight();
                robot.turnRight();
            }
            
            robot.turnRight();
            dir = (dir+90)%360;
        }
    }
}

LeetCode [518] Coin Change 2

 518. Coin Change 2

Medium

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.

     

    Example 1:

    Input: amount = 5, coins = [1, 2, 5]
    Output: 4
    Explanation: there are four ways to make up the amount:
    5=5
    5=2+2+1
    5=2+1+1+1
    5=1+1+1+1+1
    

    Example 2:

    Input: amount = 3, coins = [2]
    Output: 0
    Explanation: the amount of 3 cannot be made up just with coins of 2.
    

    Example 3:

    Input: amount = 10, coins = [10] 
    Output: 1
    

     

    Note:

    You can assume that

    • 0 <= amount <= 5000
    • 1 <= coin <= 5000
    • the number of coins is less than 500
    • the answer is guaranteed to fit into signed 32-bit integer
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    class Solution {
        public int change(int amount, int[] coins) {
                    int[] dp = new int[amount + 1];
            dp[0] = 1;
    
            for(int c : coins){
                for(int j=c; j<=amount; ++j){
                    dp[j] += dp[j-c];
                }
            }
    
            return dp[amount];
        }
    }
    

    LeetCode [630] Course Schedule III

     630. Course Schedule III

    Hard

    There are n different online courses numbered from 1 to n. Each course has some duration(course length) t and closed on dth day. A course should be taken continuously for t days and must be finished before or on the dth day. You will start at the 1st day.

    Given n online courses represented by pairs (t,d), your task is to find the maximal number of courses that can be taken.

    Example:

    Input: [[100, 200], [200, 1300], [1000, 1250], [2000, 3200]]
    Output: 3
    Explanation: 
    There're totally 4 courses, but you can take 3 courses at most:
    First, take the 1st course, it costs 100 days so you will finish it on the 100th day, and ready to take the next course on the 101st day.
    Second, take the 3rd course, it costs 1000 days so you will finish it on the 1100th day, and ready to take the next course on the 1101st day. 
    Third, take the 2nd course, it costs 200 days so you will finish it on the 1300th day. 
    The 4th course cannot be taken now, since you will finish it on the 3300th day, which exceeds the closed date.
    

     

    Note:

    1. The integer 1 <= d, t, n <= 10,000.
    2. You can't take two courses simultaneously.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    class Solution {
        public int scheduleCourse(int[][] courses) {
            Arrays.sort(courses, (a,b) -> (a[1]-b[1]));//sort by end time in increasing order
            PriorityQueue<Integer> pq = new PriorityQueue<>((a,b) -> b-a);
            int time = 0;
            for(int[] c : courses){
                time += c[0];
                pq.add(c[0]);
                if(time>c[1]) time -= pq.poll();
            }
            return pq.size();
        }
    }
    

    LeetCode [645] Set Mismatch

     645. Set Mismatch

    Easy

    The set S originally contains numbers from 1 to n. But unfortunately, due to the data error, one of the numbers in the set got duplicated to another number in the set, which results in repetition of one number and loss of another number.

    Given an array nums representing the data status of this set after the error. Your task is to firstly find the number occurs twice and then find the number that is missing. Return them in the form of an array.

    Example 1:

    Input: nums = [1,2,2,4]
    Output: [2,3]
    

    Note:

    1. The given array size will in the range [2, 10000].
    2. The given array's numbers won't have any order.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    class Solution {
        public int[] findErrorNums(int[] nums) {
            int n = nums.length;
            for(int i=0; i<n; ++i){
                while(nums[i]!=nums[nums[i]-1]){
                    int t = nums[nums[i]-1];
                    nums[nums[i]-1] = nums[i];
                    nums[i] = t;
                }
            }
    
            int[] ret = new int[2];
            for(int i=0; i<n; ++i){
                if(nums[i]!=i+1){
                    ret[0] = nums[i];
                    ret[1] = i+1;
                }
            }
            return ret;
        }
    }
    

    LeetCode [652] Find Duplicate Subtrees

     652. Find Duplicate Subtrees

    Medium

    Given the root of a binary tree, return all duplicate subtrees.

    For each kind of duplicate subtrees, you only need to return the root node of any one of them.

    Two trees are duplicate if they have the same structure with the same node values.

     

    Example 1:

    Input: root = [1,2,3,4,null,2,4,null,null,4]
    Output: [[2,4],[4]]
    

    Example 2:

    Input: root = [2,1,1]
    Output: [[1]]
    

    Example 3:

    Input: root = [2,2,2,3,null,3,null]
    Output: [[2,3],[3]]
    

     

    Constraints:

    • The number of the nodes in the tree will be in the range [1, 10^4]
    • -200 <= Node.val <= 200
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    /**
     * 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 {
        Map<String, Integer> map = new HashMap<>();
        List<TreeNode> ret = new ArrayList<>();
        public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
            helper(root);
            return ret;
        }
        
        String helper(TreeNode node){
            if(node==null) return "#";
            String s = node.val + "," + helper(node.left) + "," + helper(node.right);
            if(map.getOrDefault(s, 0)==1) ret.add(node);
            map.put(s, map.getOrDefault(s,0)+1);
            return s;
        }
    }
    

    LeetCode [679] 24 Game

     679. 24 Game

    Hard

    You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated through *, /, +, -, (, ) to get the value of 24.

    Example 1:

    Input: [4, 1, 8, 7]
    Output: True
    Explanation: (8-4) * (7-1) = 24
    

    Example 2:

    Input: [1, 2, 1, 2]
    Output: False
    

    Note:

    1. The division operator / represents real division, not integer division. For example, 4 / (1 - 2/3) = 12.
    2. Every operation done is between two numbers. In particular, we cannot use - as a unary operator. For example, with [1, 1, 1, 1] as input, the expression -1 - 1 - 1 - 1 is not allowed.
    3. You cannot concatenate numbers together. For example, if the input is [1, 2, 1, 2], we cannot write this as 12 + 12.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    class Solution {
       final double e = 0.001;
        public boolean judgePoint24(int[] nums) {
            List<Double> list = new ArrayList<>();
            for(int n:nums) list.add((double)n);
            return helper(list);
        }
    
        boolean helper(List<Double> list){
            if(list.size()==1){
                return Math.abs(list.get(0)-24) < e;
            }
    
            for(int i=0; i<list.size(); ++i){
                for(int j=i+1; j<list.size(); ++j){
                    List<Double> tmp = new ArrayList<>();
                    double v1 = list.get(i), v2 = list.get(j);
                    tmp.addAll(Arrays.asList(v1+v2, v1-v2, v2-v1, v1*v2));
                    if(Math.abs(v1)>e) tmp.add(v2/v1);
                    if(Math.abs(v2)>e) tmp.add(v1/v2);
    
                    list.remove(j);
                    list.remove(i);
                    for(double v : tmp){
                        list.add(v);
                        if(helper(list)) return true;
                        list.remove(list.size()-1);
                    }
                    list.add(i, v1);
                    list.add(j, v2);
                }
            }
            return false;
        }
    }
    

    LeetCode [690] Employee Importance

     690. Employee Importance

    Easy

    You are given a data structure of employee information, which includes the employee's unique id, their importance value and their direct subordinates' id.

    For example, employee 1 is the leader of employee 2, and employee 2 is the leader of employee 3. They have importance value 15, 10 and 5, respectively. Then employee 1 has a data structure like [1, 15, [2]], and employee 2 has [2, 10, [3]], and employee 3 has [3, 5, []]. Note that although employee 3 is also a subordinate of employee 1, the relationship is not direct.

    Now given the employee information of a company, and an employee id, you need to return the total importance value of this employee and all their subordinates.

    Example 1:

    Input: [[1, 5, [2, 3]], [2, 3, []], [3, 3, []]], 1
    Output: 11
    Explanation:
    Employee 1 has importance value 5, and he has two direct subordinates: employee 2 and employee 3. They both have importance value 3. So the total importance value of employee 1 is 5 + 3 + 3 = 11.
    

     

    Note:

    1. One employee has at most one direct leader and may have several subordinates.
    2. The maximum number of employees won't exceed 2000.
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    /*
    // Definition for Employee.
    class Employee {
        public int id;
        public int importance;
        public List<Integer> subordinates;
    };
    */
    
    class Solution {
        Map<Integer, Employee> map;
        public int getImportance(List<Employee> employees, int id) {
            map = new HashMap<>();
            for(Employee e : employees){
                map.put(e.id, e);
            }
            return helper(id);
        }
    
        int helper(int id){
            int ret = map.get(id).importance;
            for(int s : map.get(id).subordinates){
                ret += helper(s);
            }
            return ret;
        }
    }
    

    写完code之后问了时间空间复杂度,follow-up问如果访问多次应该怎样改code,以及如果不是tree就是普通的graph题应该怎么解

    但是一开始会问什么样的input data是valid的,讨论了半天,后来说必须是tree structure,然后问充要条件。我一直没想通为什么非得是tree(虽然lc上那题确实有这个条件,但感觉只是为了简单),我觉得只要是无圈图就行。。。然后follow up是如果要频繁调用的话,如何修改提高效率,就是加个记忆化,空间换时间,他说可以,不过改完就没时间了(45分钟,我也不知道为啥不能延长点),看地里说还有follow up是问如果是一般的图怎么做,我一脸问号,不知道有什么区别,按我理解只要有向无圈图总是有唯一子代树的,当时肥肠紧张以至于没敢和他argue,后来肥肠后悔,主要那老哥特别高冷,问什么就答一两个词那种,搞得人心态很差