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];
        }
  • 相关阅读:
    JavaScript 随机产生十个整数,放入数组中,对这个数组进行降序排序,并获取到这个数组的最大值和最小值
    JavaScript输出换行
    JavaScript超时调用、间歇调用
    JavaScript内置对象
    JavaScript事件列表
    JavaScript 中 for-in和 for-of 的区别
    JavaScript break指定标签打破多层循环示例
    初识JavaScript
    HTML + CSS CSS设置背景图片后图片没有铺满屏幕等
    设计模式之工厂模式
  • 原文地址:https://www.cnblogs.com/savageclc26/p/4871140.html
Copyright © 2011-2022 走看看