"Prove safety offer" Recursive, stacks and queues, backtracking (cow-off 10.27)

Difficulty topic Knowledge Point
07. Fibonacci number Recursive recursive - written two variables -
08. jump stairs Ditto
09. metamorphosis jump stairs dp
10. The rectangular footprint Ditto
05. queue with two stacks simulation
20. The stack includes a function min Stack
21. The press-pop stack sequence Stack simulated sequence
65. The path matrix Backtracking
66. The range of motion of the robot dfs communication request block size

07--10 Fibonacci number - recursive recursive - two variables wording

07. Fibonacci number

T7: We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0). n <= 39.

class Solution {
public:
    int Fibonacci(int n) {
        if(n==0) return 0;
        if(n==1) return 1;
        if(n==2) return 1;
        return Fibonacci(n-1)+Fibonacci(n-2);
    }
};

08. jump stairs

T8: a frog can jump on a Class 1 level, you can also hop on level 2. The frog jumped seeking a total of n grade level how many jumps (the order of different calculation different results).

// 两变量
class Solution {
public:
    int jumpFloor(int number) {
        if(number==0)return 1;
        if(number==1)return 1;
        if(number==2)return 2;
        int f=1,g=2;
        number-=2;
        while(number--){
            g=f+g;
            f=g-f;
        }
        return g;
    }
};

09. metamorphosis jump stairs

T9: a frog can jump on a Class 1 level, you can also hop on level 2 ...... n It can also jump on stage. The frog jumped seeking a total of n grade level how many jumps.

// dp
class Solution {
public:
    int jumpFloorII(const int number) {
        int** dp=new int*[number+10];
        for(int i=0;i<number+10;i++){
            dp[i]=new int[number+10];
        }
        
        memset(dp,0,sizeof dp);
        
        for(int i=1;i<=number;i++){
            dp[1][i]=1;
        }
        // dp[i][j] 用i步跳上台阶j
        for(int i=2;i<=number;i++){
            for(int j=i;j<=number;j++){
                for(int k=i-1;k<j;k++){
                    dp[i][j]+=dp[i-1][k];
                }
            }
        }
        
        int ans=0;
        for(int i=1;i<=number;i++){
            ans+=dp[i][number];  
        }
        return ans;// 返回的变量打错,不可原谅,,
    }
};

10. The rectangular footprint

T10: We can use a small rectangle 2 * 1 sideways or vertically to cover a larger rectangle. Will the small rectangle of n 2 * 1 coverage without overlap a large rectangle 2 * n, a total of how many ways?

Similar to the previous few questions.

class Solution {
public:
    int rectCover(int number) {
        if(number==0)    return 0;
        if(number==1)    return 1;
        if(number==2)    return 2;
        int f=1,g=2;
        number-=2;
        while(number--){
            g=f+g;
            f=g-f;
        }
        return g;
    }
};

05. queue with two stacks

Two stacks to achieve a queue, the completion queue Push and Pop operations. Queue elements int.

Received into queue element stack 1, stack 2 out of the storage elements of the queue, when the stack 2 is empty, the stack element 1 in the stack down to 2.

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }

    int pop() {
        if(stack2.size()==0){
            while(!stack1.empty()){
                int x=stack1.top();
                stack1.pop();
                stack2.push(x);
            }
        }
        int x=stack2.top();
        stack2.pop();
        return x;
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};

20. The stack includes a function min

Stack

Title Description

Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).

Each one pair of press-fitting elements (element current and the minimum current).

Java Code

import java.util.Stack;
public class Solution {
    private Stack
   
   
    
     st=new Stack<>();
    public void push(int node) {
        int min=node;
        if(!st.empty()) min=Math.min(min,st.peek());
        st.push(node);
        st.push(min);
    }
    public void pop() {
        st.pop();
        st.pop();
    }
    public int top() {
        int x=st.peek();
        st.pop();
        int y=st.peek();
        st.push(x);
        return y;
    }
    public int min() {
        return st.peek();
    }
}
    
   
   

More space-saving approach is as follows:
Application of an auxiliary stack when the pressure, if the pressure of the stack A is greater than B is pressed into the stack, the stack is not pressed B ,,,, less, AB pressed while the stack, the stack, if , AB ranging from the top element, A a, B no.

21. The stack is pressed into the pop-up sequence

simulation

Title Description

Two input sequence of integers, the first sequence representing a pressed stack order, determines whether it is possible for the second sequence the order of the pop-up stack. All figures are not pushed onto the stack is assumed equal. Such as a sequence of a sequence of 1,2,3,4,5 is pressed into the stack, the push sequence is 4,5,3,2,1 sequence corresponding to a sequence of pop, but 4,3,5,1,2 it is impossible to push pop-up sequence of the sequence. (Note: the length of the two sequences are equal)

import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        if(pushA.length == 0 || popA.length == 0)
            return false;
        Stack<Integer> s = new Stack<Integer>();
        //用于标识弹出序列的位置
        int popIndex = 0;
        for(int i = 0; i< pushA.length;i++){
            s.push(pushA[i]);
            //如果栈不为空,且栈顶元素等于弹出序列
            while(!s.empty() &&s.peek() == popA[popIndex]){
                //出栈
                s.pop();
                //弹出序列向后一位
                popIndex++;
            }
        }
        return s.empty();
    }
}

65. The matrix of path

Backtracking

Title Description

Please design a function that determines whether there is a route that contains all the characters of a character string in a matrix. A lattice path may start from any of the matrix, each step in the matrix can be left, right, up, down one grid. If a route that passes through a matrix of a grid, the path can not enter the lattice. E.g. abcesfcsdee matrix containing the path "bcced" in a string, but does not contain the matrix "abcb" path, as a character string in the first row of the matrix b occupy the first lattice after the second path can not be again access to the grid.

dfs back.

Java Code

public class Solution {
    private int rows, cols;
    char[][] G;
    char[] str;
    boolean[][] vis;
    int[] dx = new int[]{1, 0, -1, 0};
    int[] dy = new int[]{0, 1, 0, -1};
    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        if (matrix == null || matrix.length < str.length)
            return false;
        this.str = str;
        this.rows = rows;
        this.cols = cols;
        G = new char[rows][cols];
        vis = new boolean[rows][cols];
        for (int i = 0; i < matrix.length; i++) {
            G[i / cols][i % cols] = matrix[i];
        }
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (G[i][j] == str[0]) {
                    if (str.length == 1) return true;
                    vis[i][j] = true;
                    for (int k = 0; k < 4; k++) {
                        if (check(i + dx[k], j + dy[k])
                                && dfs(i + dx[k], j + dy[k], 1))
                            return true;
                    }
                    vis[i][j] = false;
                }
            }
        }
        return false;
    }
    private boolean dfs(int x, int y, int idx) {
        if (G[x][y] != str[idx]) return false;
        if (idx == str.length - 1) return true;
        vis[x][y] = true;
        for (int k = 0; k < 4; k++) {
            if (check(x + dx[k], y + dy[k])
                    && dfs(x + dx[k], y + dy[k], idx + 1))
                return true;
        }
        vis[x][y] = false;
        return false;
    }
    private boolean check(int x, int y) {
        return x >= 0 && x < rows && y >= 0 && y < cols && !vis[x][y];
    }
}
    

66. The range of motion of the robot

dfs communication request block size

Title Description
ground there is a grid of m rows and n columns. A robot moves from the grid coordinates 0,0, every time only left, right, upper, lower four directions a cell, but can not enter the row and column coordinates of the grid is greater than the sum of the number of bits k. For example, when k is 18, the robot can enter the box (35, 37), because 3 + 3 + 5 + 7 = 18. However, it can not enter the box (35, 38), because 3 + 3 + 5 + 8 = 19. Will the robot be able to reach the number of lattice?

dfs communication request block size. Note that use array vis avoid double-counting.

Java Code

public class Solution {
    int cnt=0;
    boolean [][]vis;
    public int movingCount(int threshold, int rows, int cols)
    {
        vis=new boolean[rows][cols];
        dfs(0,0,rows,cols,threshold);
        return cnt;
    }
    private void dfs(int x,int y,int rows,int cols,int thrsh){
        if(!check(x,y,rows,cols,thrsh))  return;
        cnt++;
        vis[x][y]=true;
        dfs(x,y+1,rows,cols,thrsh);
        dfs(x+1,y,rows,cols,thrsh);
        dfs(x,y-1,rows,cols,thrsh);
        dfs(x-1,y,rows,cols,thrsh);
    }
    private boolean check(int x,int y,int rows,int cols,int thrsh){
        if(x<0||x>=rows||y<0||y>=cols||vis[x][y])    return false;
        int sum=0;
        while(x>0){ sum+=x%10;x/=10; }
        while(y>0){ sum+=y%10;y/=10; }
        return sum<=thrsh;
    }
}
    

Guess you like

Origin www.cnblogs.com/weseewe/p/11750123.html