zoukankan      html  css  js  c++  java
  • LeetCode 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?

    有道翻译:

    一个机器人位于左上角的m x n网格(下图中标记为“开始”)。

    机器人任意时候只能向下或者向右移动,机器人尝试到达右下角,求有多少种方法

    思路:用动态规划的思考方式去求解,申请额外空间dp[m][n],dp[i][j]表示当以{i,j}为右下角的时候的,机器人移动到该位置的方法,

    dp[i][j]的决策方案:

        1、机器人从dp[i-1][j]到达{i,j}的位置,也就是从{i-1,j}的位置向下移动到{i,j}

        2、机器人从dp[i][j-1]到达{i,  j}的位置,也就是从{j,j-1}的位置向右移动到{i, j}

        所以dp[i][j] = dp[i-1][j] + dp[i][j-1];

    public class Solution {
    
         public int uniquePaths(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][j - 1] + dp[i - 1][j];
                }
            }
            return dp[m - 1][n - 1];
        }
    }

    空间优化以后的代码:

    public class Solution {
    
        public int uniquePaths(int m, int n){
    
            int[] dp = new int[n];
            for (int i = 0; i < n; i++) {
                dp[i] = 1;
            }
    
            for (int i = 1; i < m; i++) {
                for (int j = 1; j < n; j++) {
                    dp[j] = dp[j - 1] + dp[j];
                    System.out.println(dp[j]);
                }
            }
            return dp[n - 1];
        }
    
        public static void main(String[] args) {
            Solution s = new Solution();
            int num = s.uniquePaths(2, 62);
            System.out.println(num);
        }
    }
  • 相关阅读:
    实例协议分析RFC1483:AAL5和几种常见ADSL接入技术
    2.2.3 Runaround Numbers
    2.2.2 Subset Sums
    2.2.1 Preface Numbering
    Dynamic Programming
    Data Structures
    2.1.5 Hamming Codes
    2.1.4 Healthy Holsteins
    2.1.3 Sorting a Three-Valued Sequence
    2.1.2 Ordered Fractions
  • 原文地址:https://www.cnblogs.com/googlemeoften/p/5835488.html
Copyright © 2011-2022 走看看