zoukankan      html  css  js  c++  java
  • [LeetCode]: 62: 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).

    How many possible unique paths are there?

    Above is a 3 x 7 grid. How many possible unique paths are there?

    Note: m and n will be at most 100.

    思路1:递归

    终点的路径数= 所有能达到终点的点的路径数之和,即为:路径[m][n] = 路径[m-1][n] + 路径[m][n-1]

    依次递归,直到start点(0,0)

    代码:

        public static int uniquePaths(int m, int n) {
            if(n == 1 && m==1){
                //初始的位置
                return 1;
            }
            else if(n == 1 && m>1){
                return uniquePaths(1,m-1);
            }
            else if(n >1 && m==1){
                return uniquePaths(n-1,1);
            }
            else{
                return uniquePaths(n-1,m)+uniquePaths(n,m-1);
            }
        }

    结果在m=17 n=23的时候超时了。所以意识到题目的限制条件是需要速度!

    思路2:动态规划

    某一个点的路径数= 所有能达到该点的点的路径数之和,即为:路径[m][n] = 路径[m-1][n] + 路径[m][n-1]

    与递归不同的是,递归是从大往小算,动态规划是从小往大算

    代码如下:

        public static int uniquePaths(int m, int n) {
            int[][] arrResult  = new int[m][n];
            
            for(int i = 0;i<m;i++){
                for(int j = 0;j<n;j++){
                    if(i == 0 && j== 0){  
                        arrResult[0][0] = 1;
                    }
                    else if(i == 1 && j== 0){
                        arrResult[1][0] = 1;
                    }else if(i == 0 && j== 1){
                        arrResult[0][1] = 1;
                    }
                    //以上是填充基础值
                    else{
                        int row = 0;
                        int column  = 0;
                        
                        if(i> 0 ){
                            row = arrResult[i-1][j];
                        }
                        
                        if(j> 0 ){
                            column = arrResult[i][j-1];
                        }
    
                        arrResult[i][j] = row + column;    
                    }
                }
            }
            
            
            return arrResult[m-1][n-1];
        }
  • 相关阅读:
    Xshell 使用纪要
    矩阵求逆
    Ubuntu 增加新用户
    matlab 常用图像处理
    Surface Evolver 基本操作、使用指南和珍贵资料
    latex 裁剪图片
    Inkscape 输入希腊字母
    Pyton——int内部功能介绍
    python——登陆接口设计(循环方法)
    Python之三层菜单
  • 原文地址:https://www.cnblogs.com/savageclc26/p/4871140.html
Copyright © 2011-2022 走看看