Preparing for the intervies of FLAG and USDA

Posted 创业者-春跃-增长黑客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Preparing for the intervies of FLAG and USDA相关的知识,希望对你有一定的参考价值。

7,Dynamic Programming

1,Unique Paths

A robot is located at the top-left corner of a m x n grid (marked \'Start\' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked \'Finish\' in the diagram below).
View Code

Analyse:

public class Solution {
    public int uniquePaths(int m, int n)
    {
        int[][] dp = new int[m][n];
        for (int i = 0; i < n; i++) {
            dp[0][i] = 1;
        }
        for (int i = 0; i < m; i++) {
            dp[i][0] = 1;
        }
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        return dp[m - 1][n - 1];
    }
}
View Code

滚动指针来优化空间复杂度:

public class Solution {
    public int uniquePaths(int m, int n)
    {
        int[][] dp = new int[2][n];
        for (int i = 0; i < n; i++) {
            dp[0][i] = 1;
        }
        dp[0][0] = 1;
        for (int i = 1; i < m; i++) {
            dp[i % 2][0] = 1;
            for (int j = 1; j < n; j++) {
                dp[i % 2][j] = dp[(i - 1) % 2][j] + dp[i % 2][j - 1];
            }
        }
        return dp[(m - 1) % 2][n - 1];
    }
}
View Code

1--follow up :有障碍物。

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0) {
            return 0;
        }
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] dp = new int[m][n];
        // initialize
        for (int i = 0; i < m; i++) {
            if (obstacleGrid[i][0] != 1) {
                dp[i][0] = 1;
            } else {
                break;
            }
        }
        for (int j = 0; j < n; j++) {
            if (obstacleGrid[0][j] != 1) {
                dp[0][j] = 1;
            } else {
                break;
            }
        }
        // calculate
        for (int i = 1; i < m; i++) {
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] != 1) {
                    dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
                }
            }
        }
        return dp[m - 1][n - 1];
    }
}
View Code

滚动数组优化:

public class Solution {
    public int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid == null || obstacleGrid.length == 0) {
            return 0;
        }
        int m = obstacleGrid.length;
        int n = obstacleGrid[0].length;
        int[][] dp = new int[2][n];
        for (int j = 0; j < n; j++) {
            if (obstacleGrid[0][j] != 1) {
                dp[0][j] = 1;
            } else {
                break;
            }
        }
        // calculate
        for (int i = 1; i < m; i++) {
            if (dp[(i - 1) % 2][0] != 0 && obstacleGrid[i][0] != 1) {
                dp[i % 2][0] = 1;
            } else {
                dp[i % 2][0] = 0;
            }
            for (int j = 1; j < n; j++) {
                if (obstacleGrid[i][j] != 1) {
                    dp[i % 2][j] = dp[(i - 1) % 2][j] + dp[i % 2][j - 1];
                } else {
                    dp[i % 2][j] = 0;
                }
            }
        }
        return dp[(m - 1) % 2][n - 1];
    }
}
View Code

 

2,Minimum Path Sum

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.
View Code

Analyse:

public class Solution {
    public int minPathSum(int[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        int m = grid.length;
        int n = grid[0].length;
        int[][] dp = new int[2][n];
        dp[0][0] = grid[0][0];
        // for (int i = 1; i < m; i++) {
        //     dp[i][0] = dp[i - 1][0] + grid[i][0];
        // }
        for (int j = 1; j < n; j++) {
            dp[0][j] = dp[0][j - 1] + grid[0][j];
        }
        for (int i = 1; i < m; i++) {
            dp[i % 2][0] = dp[(i - 1) % 2][0] + grid[i][0];
            for (int j = 1; j < n; j++) {
                dp[i % 2][j] = Math.min(dp[(i - 1) % 2][j], dp[i % 2][j - 1]) + grid[i][j];
            }
        }
        return dp[(m - 1) % 2][n - 1];
    }
}
View Code

3,climb stairs

You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Subscribe to see which companies asked this question
View Code

Analyse:

public class Solution {
    public int climbStairs(int n) {
        if (n <= 0) {
            return 0;
        }
        if (n <= 2) {
            return n;
        }
        int[] dp = new int[2];
        dp[0] = 1;
        dp[1] = 2;
        for (int i = 2; i < n; i++) {
            dp[i % 2] = dp[(i - 1) % 2] + dp[(i - 2) % 2];
        }
        return dp[(n - 1) % 2];
    }
}
View Code

4,maximum subarray

public class Solution {
    public int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int[] dp = new int[2];
        int max = nums[0];
        dp[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            dp[i % 2] = Math.max(dp[(i - 1) % 2] + nums[i], nums[i]);
            max = Math.max(max, dp[i % 2]);
        }
        return max;
    }
}
View Code

5,triangle

public class Solution {
    public int minimumTotal(List<List<Integer>> triangle) {
        if (triangle == null || triangle.size() == 0) {
            return 0;
        }
        int size = triangle.size(); 
        for (int i = size - 2; i >= 0; i--) {
            // find the min
            for (int j = 0; j <= i; j++) {
                triangle.get(i).set(j, triangle.get(i).get(j) + Math.min(triangle.get(i + 1).get(j), triangle.get(i + 1).get(j + 1)));
            }
        }
        return triangle.get(0).get(0);
    }
}
View Code

6,best time to buy and sell stock

public class Solution {
    public int maxProfit(int[] prices) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int minPrice = prices[0];
        int maxProfit = 0;
        for (int i = 1; i < prices.length; i++) {
            minPrice = Math.min(minPrice, prices[i]);
            maxProfit = Math.max(maxProfit, prices[i] - minPrice);
        }
        return maxProfit;
    }
}
View Code

7,

 

6,Recursion

1,climb building (print all the possible ways)

Analyse:

public class Solution {
    public static void main(String[] args) {
        climb(3, "");
    }
    public static void climb(int n, String preWay) {
        if (n == 1) {
            System.out.println(preWay + " 1");
            return;
        }
        if (n == 2) {
            System.out.println(preWay + " 2");
            System.out.println(preWay + " 1 1");
            return;
        }
        String preWay1 = preWay + " 1";
        climb(n - 1, preWay1);
        String preWay2 = preWay + " 2";
        climb(n - 2, preWay2);
    }
}
View Code

 

2,Hanoi

Analyse : Move the first (n - 1) disk from A to B; then move the nth disk from A to C; move the other (n - 1) disk from b to c.

(1) how many steps we need to move all n disks from A to C.

import java.io.*;
class test  
{
    public static void main (String[] args) {
        System.out.println(hanoiSteps(3));
    }
    public static int hanoiSteps(int n) {
        if (n == 1) {
            return 1;
        }
        return hanoiSteps(n - 1) + 1 + hanoiSteps(n - 1);
    }
    
}
View Code

 

(2) Print all the steps that is needed to move all n disks from A to C.

import java.io.*;
class test  
{
    public static void hanoi(int n, char source, char spare, char target) {
        if (n == 1) {
            System.out.println("Move " + source + " to " + target);
            return;
        }
        hanoi(n - 1, source, target, spare);
        System.out.println("Move " + source + " to " + target);
        hanoi(n - 1, spare, source, target);
    }
    
}
View Code

 

(3) 0-1 knapsack

Given a knapsack which can hold s pounds of items, and a set of items with weight w1, w2, ... wn. Return whether we can pick specific items so that their total weight s. 
View Code

Analyse: pick it: (s - w[i], w - w[i]), or not pick it : (s, w - w[i]);

import java.io.*;
class test  
{
    public static void main(String[] args) {
        int[] weights = {14, 8, 7, 5, 3};
        System.out.println(knapsack(20, weights, 0));
    }
    public static boolean knapsack(int s, int[] weights, int index) {
        if (s == 0) {
            return true;
        }
        if (s < 0 || index >= weights.length) {
            return false;
        }
        return knapsack(s - weights[index], weights, index + 1) || knapsack(s, weights, index + 1);
    }
    
}
View Code

 (4)0-1 knapsack

0-1 Knapsack II
Given a knapsack which can hold s pounds of items, and a set of items with
weight w1, w2, ... wn. Try to put items into the pack as many as possible, return
the largest weight we can get in the knapsack.
View Code

Analyse : pick it weights[index] + knapsack2, index + 1; not pick it : knapsack2,  index + 1;

public class Solution {
    public int getMax(int s, int[] weights) {
        return knapsack2(s, weights, 0);
    }
    public static int knapsack2(int s, int[] weights, int index) {
        if (s == 0 || index == weights.length) {
            return 0;
        }
        if (weights[index] > s) {
            return knapsack2(s, weights, index + 1);
        }
        return Math.max(knapsack2(s, weights, index + 1), weights[index] + knapsack2(s - weights[index], weights, index + 1));
    }
}
View Code

(5) knapsack III

Knapsack III
Given a set of candidate numbers (C) and a target number (T), find all unique
combinations in C where the candidate numbers sums to T.
All candidate numbers are unique.
The same repeated number may be chosen from C unlimited number of times.
View Code

Analyse :

import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> cur = new ArrayList<Integer>();
        combine(candidates, 0, target, results, cur);
        return results;
    }
    public void combine(int[] candidates, int index, int target,
            ArrayList<ArrayList<Integer>> results,
            ArrayList<Integer> cur) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            results.add(new ArrayList<Integer>(cur));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            cur.add(candidates[i]);
            combine(candidates, i, target-candidates[i], results, cur);
            cur.remove(cur.size()-1);
        }
        return;
    }
}
View Code

 

(6) knapsack III-2

Given a collection of candidate numbers (C) and a target number (T), find all
unique combinations in C where the candidate numbers sums to T.
Candidate numbers may contain duplicate.
Each number in C may only be used once in the combination.
View Code
import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> cur = new ArrayList<Integer>();
        combine(candidates, 0, target, results, cur);
        return results;
    }
    public void combine(int[] candidates, int index, int target,
            ArrayList<ArrayList<Integer>> results,
            ArrayList<Integer> cur) {
        if (target < 0) {
            return;
        }
        if (target == 0) {
            results.add(new ArrayList<Integer>(cur));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            cur.add(candidates[i]);
            combine(candidates, i + 1, target-candidates[i], results, cur);
            cur.remove(cur.size()-1);
            while (i < candidates.length - 1 && candidates[i] == candidates[i + 1]) {
                i++;
            }
        }
        return;
    }
}
View Code

 

(7) maze

Maze
Given a maze and a start point and a target point, return whether the target can
be reached.
Example Input:
Start Point: (0, 0); Target Point (5, 5);
Maze: char[][] = {
{\'.\', \'X\', \'.\', \'.\', \'.\', \'X\'},
{\'.\', \'.\', \'.\', \'X\', \'.\', \'X\'},
{\'X\', \'X\', \'.\', \'X\', \'.\', \'.\'},
{\'.\', \'X\', \'X\', \'X\', \'.\', \'X\'},
{\'.\', \'.\', \'.\', \'.\', \'.\', \'X\'},
{\'.\', \'.\', \'.\', \'.\', \'.\', \'.\'}
}
Example Output: True
View Code

Analyse:bfs

1,return whether the target can be reached

public class Solution {
    public static void main(String[] args) {
        char[][] maze= {
                {\'.\', \'X\', \'.\', \'.\', \'.\', \'X\'},
                {\'.\', \'.\', \'.\', \'X\', \'.\', \'X\'},
                {\'X\', \'X\', \'.\', \'X\', \'.\', \'.\'},
                {\'.\', \'X\', \'X\', \'X\', \'.\', \'X\'},
                {\'.\', \'.\', \'.\', \'.\', \'.\', \'X\'},
                {\'.\', \'.\', \'.\', \'.\', \'.\', \'.\'}
                };
        System.out.println(solveMaze(maze, 0, 0, 5, 5));
    }
    public static boolean solveMaze(char[][] maze, int startX, int startY, int targetX, int targetY) {
        if (startX == targetX && startY == targetY) {
            return true;
        }
        maze[startX][startY] = \'X\';
        int[] dx = {1, 0, -1, 0};
        int[] dy = {0, 1, 0, -1};
        for (int i = 0; i < 4; i++) {
            int newX = startX + dx[i];
            int newY = startY + dy[i];
            if (newX < 0 || newX >= maze.length || newY < 0 || newY >= maze[0].length || maze[newX][newY] == \'X\') {
                continue;
            }
            if (solveMaze(maze, newX, newY, targetX, targetY)){
                return true;
            }
        }
        return false;
    }
}
View Code

2,print out the path to reach the target.

import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public static void main(String[] args) {
        ArrayList<Character> list = new ArrayList();
        char[][] maze= {
                {\'.\', \'X\', \'.\', \'.\', \'.\', \'X\'},
                {\'.\', \'.\', \'.\', \'X\', \'.\', \'X\'},
                {\'X\', \'X\', \'.\', \'X\', \'.\', \'.\'},
                {\'.\', \'X\', \'X\', \'X\', \'.\', \'X\'},
                {\'.\', \'.\', \'.\', \'.\', \'.\', \'X\'},
                {\'.\', \'.\', \'.\', \'.\', \'.\', \'.\'}
                };
        System.out.println(solveMaze(maze, 0, 0, 5, 5, list));
        System.out.println(list);
    }
    public static boolean solveMaze(char[][] maze, int startX, int startY, int targetX, int targetY, ArrayList<Character> path) {
        if (startX == targetX && startY == targetY) {
            return true;
        }
        maze[startX][startY] = \'X\';
        int[] dx = {1, 0, -1, 0};
        int[] dy = {0, 1, 0, -1};
        char[] direction = {\'R\', \'U\', \'L\', \'D\'};
        for (int i = 0; i < 4; i++) {
            int newX = startX + dx[i];
            int newY = startY + dy[i];
            path.add(direction[i]);
            if (newX < 0 || newX >= maze.length || newY < 0 || newY >= maze[0].length || maze[newX][newY] == \'X\') {
                continue;
            }
            if (solveMaze(maze, newX, newY, targetX, targetY, path)){
                return true;
            }
            path.remove(path.size() - 1);
        }
        return false;
    }
}
View Code

(8) generate parentheses

22. Generate Parentheses  QuestionEditorial Solution  My Submissions
Total Accepted: 96789
Total Submissions: 251907
Difficulty: Medium
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]
View Code

Analyse: use left and right to remeber the leaved numbers of left parenthesis and right parenthesis. left == 0 && right == 0, put the string into list.

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> results = new ArrayList();
        generateParenthesis(results, "", n, n);
        return results;
    }
    public static void generateParenthesis(List<String> results, String prefix, int left, int right) {
        if (left == 0 && right == 0) {
            results.add(prefix);
            return;
   

以上是关于Preparing for the intervies of FLAG and USDA的主要内容,如果未能解决你的问题,请参考以下文章

运行真机提示Errors were encountered while preparing your device for development. Please check the Devices

Errors were encountered while preparing your device for development. Please check the Devices and Si

Errors were encountered while preparing your device for development. Please check the Devices and Si

Errors were encountered while preparing your device for development. Please check the Devices and Si

Preparing for Merge Sort CodeForces - 847B

Preparing a toolchain for building ARM binaries on x86 hosts