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

    Unique Paths

     Total Accepted: 36748 Total Submissions: 112531My Submissions

    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.

    Hide Tags
     Array Dynamic Programming
     
    思路一: 动态规划, f[i][j] = f[i-1][j] + f[i][j-1], 且f[i][0] = 0, f[0][j]=0, f[1][1] =1 ,时间复杂度O(m*n),空间复杂度O(m*n)
    class Solution {
        public:
            int uniquePaths(int m, int n)
            {   
                vector<int> row(n + 1, 0); 
                vector<vector<int> > f(m + 1, row);
    
                f[1][1] = 1;
    
                for(int i = 1; i <= m; i ++) 
                {   
                    for(int j = 1; j <= n; j ++) 
                    {   
                        if(i == 1 && j == 1)
                            continue;
                        f[i][j] = f[i-1][j] + f[i][j-1];
                    }   
                }   
    
                return f[m][n];
            }   
    };
     思路二:空间复杂度还可以优化,将f[][] 改成 f[],优化后,时间复杂度不变,空间复杂度O(n)
     
    class Solution {
        public:
    #if 0
            int uniquePaths(int m, int n)
            {
                vector<int> row(n + 1, 0);
                vector<vector<int> > f(m + 1, row);
    
                f[1][1] = 1;
    
                for(int i = 1; i <= m; i ++)
                {
                    for(int j = 1; j <= n; j ++)
                    {
                        if(i == 1 && j == 1)
                            continue;
                        f[i][j] = f[i-1][j] + f[i][j-1];
                    }
                }
    
                return f[m][n];
            }
    #endif
            int uniquePaths(int m, int n)
            {
                vector<int> f(n + 1, 0);
    
                f[1] = 1;
    
                for(int i = 1; i <= m; i ++)
                {
                    for(int j = 1; j <= n; j ++)
                    {
                        if(i == 1 && j == 1)
                            continue;
                        f[j] = f[j] + f[j-1];
                    }
                }
    
                return f[n];
            }
    };
     
     
  • 相关阅读:
    java中equals与hashCode的重写问题
    关于java的二维码的生成与解析
    bootstrap的时间控件使用(双日历)
    Mysql表,列,库的增删查改
    关于js重名方法的先后调用问题
    javascript的比较运算符
    javascript的运算符
    JavaScript的数据类型
    javascript的基本语法
    MAP集合
  • 原文地址:https://www.cnblogs.com/diegodu/p/4320168.html
Copyright © 2011-2022 走看看