zoukankan      html  css  js  c++  java
  • [LeetCode]Unique Paths

    题目:Unique Paths

    从左上角到右下角的所有可能路径。

    思路1:

    回溯法去递归遍历所有的路径,但是复杂度太大,无法通过。checkPath方法实现

    思路2:

    动态规划法,从左上角到每一格的路径数与它的上面一格和左边一格的路径和;

    N(m,n)=N(m-1,n)+N(m,n-1);

    注意:第一行和第一列的特殊情况。

    package com.example.medium;
    
    /**
     * 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.
     * @author FuPing
     *
     */
    public class UniquePaths {
        /**
         * 回溯法
         * @param m 行边界
         * @param n 列边界
         * @param i 当前位置的行坐标
         * @param j 当前位置的列坐标
         * @return 可能的道路数量
         * 时间超过了,20*15的规模就需要7870ms的时间
         */
        private int checkPath(int m,int n,int i,int j){
            if(i == m && j == n)return 1;//到达最后一格
            int roads = 0;
            if(i < m) roads += checkPath(m,n,i+1,j);//向左
            if(j < n) roads += checkPath(m,n,i,j+1);//向下
            return roads;
        }
        /**
         * 动态规划 N(m,n)=N(m-1,n)+N(m,n-1)
         * @param m
         * @param n
         * @return
         */
        private int uniquePaths(int m, int n) {
            //return checkPath(m,n,1,1);
            int roadNums[][] = new int[m][n];
            roadNums[0][0] = 1;
            int i = 0,j = 0;
            for(i = 1;i < m;i++)roadNums[i][0] = roadNums[0][0];//第一行
            for(j = 1;j < n;j++)roadNums[0][j] = roadNums[0][0];//第一列
            i = 1;
            j = 1;
            while(i < m && j < n){
                roadNums[i][j] = roadNums[i][j - 1] + roadNums[i - 1][j];
                j++;
                if(j == n){
                    i++;
                    if(i == m)break;
                    j = 1;
                }
            }
            return roadNums[m - 1][n - 1];
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            long startTime = System.currentTimeMillis();
            System.out.println(new UniquePaths().uniquePaths(20, 50));
            long endTime = System.currentTimeMillis();
            System.out.println("程序运行时间:"+(endTime-startTime) + "ms");
    
        }
    
    }

     题目:Unique PathsII

    从左上角到右下角的所有可能路径。这次给定了网格数组,当数组值为1,表示不能通过;即设置了障碍。

    思路:

    仍然用上面动态规划的方法,只是当遇到障碍物时,该网格的值是0。

    package com.example.medium;
    
    /**
     * Follow up for "Unique Paths":
     * Now consider if some obstacles are added to the grids. How many unique paths would there be?
     * An obstacle and empty space is marked as 1 and 0 respectively in the grid.
     * For example,
     * There is one obstacle in the middle of a 3x3 grid as illustrated below.
     * [
     *   [0,0,0],
     *   [0,1,0],
     *   [0,0,0]
     * ]
     * The total number of unique paths is 2.
     * Note: m and n will be at most 100.
     * @author FuPing
     *
     */
    public class UniquePaths2 {
        /**
         * 动态规划 N(m,n)=N(m-1,n)+N(m,n-1)
         * @param m
         * @param n
         * @return
         */
        private int uniquePathsWithObstacles(int[][] obstacleGrid) {
            if(obstacleGrid[0][0] == 1)return 0;
            int m = obstacleGrid.length;//行数
            int n = obstacleGrid[0].length;//列数
            System.out.println(m + n);
            int roadNums[][] = new int[m][n];
            roadNums[0][0] = 1;//其实节点为1
            int i = 0,j = 0;
            for(i = 1;i < m;i++){//第一行
                if(obstacleGrid[i][0] == 0)roadNums[i][0] = roadNums[i - 1][0];//没有障碍时,等于左边的路径数
            }
            for(j = 1;j < n;j++){//第一列
                if(obstacleGrid[0][j] == 0)roadNums[0][j] = roadNums[0][j - 1];//没有障碍时,等于上边的路径数
            }
            i = 1;
            j = 1;
            while(i < m && j < n){
                if(obstacleGrid[i][j] == 0)
                    roadNums[i][j] = roadNums[i][j - 1] + roadNums[i - 1][j];//没有障碍时,动态规划;否则,还是默认值0
                j++;
                if(j == n){
                    i++;
                    if(i == m)break;
                    j = 1;
                }
            }
            return roadNums[m - 1][n - 1];
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            long startTime = System.currentTimeMillis();
            int matrix[][] = {{0,0,0,0,0,1,0},{0,0,0,1,0,0,0},{1,0,0,1,0,0,0}};
            System.out.println(new UniquePaths2().uniquePathsWithObstacles(matrix));
            long endTime = System.currentTimeMillis();
            System.out.println("程序运行时间:"+(endTime-startTime) + "ms");
    
        }
    
    }

    题目:Minimum Path Sum

    给定一个数组,数组中的值表示通过当前位置的路费,找一条从左上到右下路费最少的路线。

    思路:

    任然可以用动态规划法。

    N(i,j)=A(i,j) + min{N(i-1,j),N(i,j-1)};

    package com.example.medium;
    
    /**
     * 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.
     * @author FuPing
     *
     */
    public class MinPathSum {
        public int minPathSum(int[][] grid) {
            int m = grid.length;
            int n = grid[0].length;
            int pathValues[][] = new int[m][n];
            pathValues[0][0] = grid[0][0];
            int i = 0,j = 0,min = 0;
            for(i = 1;i < m;i++){//第一行
                pathValues[i][0] = pathValues[i - 1][0] + grid[i][0];
            }
            for(j = 1;j < n;j++){//第一列
                pathValues[0][j] = pathValues[0][j - 1] + grid[0][j];
            }
            i = 1;
            j = 1;
            while(i < m && j < n){
                min = pathValues[i][j - 1] > pathValues[i - 1][j] ? pathValues[i - 1][j] : pathValues[i][j - 1];//找左边和上边中较小的路径
                pathValues[i][j] = grid[i][j] + min;//更新当前的路费
                j++;
                if(j == n){//当前行遍历完
                    i++;
                    if(i == m)break;//全部遍历完
                    j = 1;
                }
            }
            return pathValues[m - 1][n - 1];
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            long startTime = System.currentTimeMillis();
            int matrix[][] = {{1,2,3,4,5,6,7},{3,4,1,3,5,2,1},{6,2,3,7,4,2,2}};
            System.out.println(new MinPathSum().minPathSum(matrix));
            long endTime = System.currentTimeMillis();
            System.out.println("程序运行时间:"+(endTime-startTime) + "ms");
        }
    
    }
  • 相关阅读:
    PHP 文件上传下载
    php文件类型MIME对照表
    如何书写安全的PHP代码
    wordpress顶部空白解决方案
    PHP发送邮件
    UTF8下面截取中文字符。
    dedecms 5.5 实现tag分页伪静态
    PHP MySQL 函数
    php异步调用
    归并排序及序列逆序数
  • 原文地址:https://www.cnblogs.com/yeqluofwupheng/p/6683456.html
Copyright © 2011-2022 走看看