leetcode brush 23 title

Today's topic is LeetCode brush 62 questions, questions asked are:

A robot located in a left corner mxn grid (starting point figure below labeled "Start").

The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").

Q. How many different paths there are in total?

This question is very simple, my first thought was backtracking algorithm, but overtime, specifically code is as follows:

private static int count;
    public static int solution(int m,int n){
        count=0;
        recursion(m,n,0,0);
        return count;
    }
    public static void recursion(int m,int n,int x,int y){
        if (x==m-1&&y==n-1){
            count++;
            return;
        }
        if (x<m){
            recursion(m,n,x+1,y);
        }
        if (y<n){
            recursion(m,n,x,y+1);
        }
    }

Then take into account the sentence, can only reach the point xy from x-1y and xy-1 two points, then you can do with dynamic programming. Specifically, the code follows

public static int dp(int m,int n){
        int[][] dp=new int[m][n];
        for (int i = 0; i <m ; i++) {
            dp[i][0]=1;
        }
        for (int i = 0; i <n ; i++) {
            dp[0][i]=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];
    }

But the above two-dimensional array of space too, can be further compressed. Imagine directly to the line number to move to this line, then the value of xy would just have to add the value of xy-1. Specifically code is as follows:

public static int dp2(int m,int n){
        int[] current=new int[n];
        Arrays.fill(current,1);
        for (int i = 1; i <m ; i++) {
            for (int j = 1; j <n ; j++) {
                current[j]+=current[j-1];
            }
        }
        return current[n-1];
    }

 

Guess you like

Origin www.cnblogs.com/cquer-xjtuer-lys/p/11482873.html