GithubHelp home page GithubHelp logo

algorithm's People

Contributors

gmlyytt-yang avatar

Stargazers

 avatar

Watchers

 avatar

algorithm's Issues

leetcode_118. Pascal's Triangle

题意

Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

Example:

Input: 5
Output:
[
     [1],
    [1,1],
   [1,2,1],
  [1,3,3,1],
 [1,4,6,4,1]
]

思路 & 实现

简单的动态规划解决问题,动态规划的公式为result[j][index] = result[j - 1][index - 1] + result[j - 1][index]。另外,需要特别注意的是边界问题,即开始遍历和停止遍历的边界判断。

如下是C++的实现方式。

class Solution {
public:
    vector<vector<int>> generate(int numRows) {
        vector<vector<int>> results;
        if (numRows <= 0) {
            return results;
        }
        
        for (int index = 0; index < numRows; ++index) {
            vector<int> row(index + 1, 1);
            for (int inner_index = 1; inner_index < index; ++inner_index) {
                row[inner_index] = results[index - 1][inner_index - 1] 
                        + results[index - 1][inner_index];
            }
            results.emplace_back(row);
        }
        
        return results;
    }
};

时空复杂度

时间复杂度:O(n^2), 遍历的次数为1+2+...+numRows-1=numRows(numRows - 1) / 2,因而时间复杂度为O(n^2)。

空间复杂度:O(n^2), 因为结果是二维数组。

leetcode_134. Gas Station

题意

There are N gas stations along a circular route, where the amount of gas at station i is gas[i].

You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.

Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.

Note:

If there exists a solution, it is guaranteed to be unique.
Both input arrays are non-empty and have the same length.
Each element in the input arrays is a non-negative integer.

Example 1:

Input: 
gas  = [1,2,3,4,5]
cost = [3,4,5,1,2]

Output: 3

Explanation:
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
Example 2:

Input: 
gas  = [2,3,4]
cost = [3,4,3]

Output: -1

Explanation:
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.

思路 & 实现

从第一站开始计算剩余油量left,如果发现剩余油量小于0,则可以证明从第一站开始到当前站(i)的下一站(i+1)中间的任何一站都没有可以设置的起点(start),因为如果从第一站起都没有办法走到i+1, 那么第一站与i+1中间的任何一站作为起点都没办法走到i+1,因而起点只可能从i+1开始寻找。

在从第一站开始遍历的过程中,还需要记录每次尝试寻找起点过程中欠下油量的累加和lack,遍历到最后需要看下剩余油量leftlack的加和是否大于0来判断是否存在起点start.

如下是C++的实现方式。

class Solution {
public:
    int canCompleteCircuit(vector<int>& gas, vector<int>& cost) {
        int length = gas.size();
        if (length != cost.size() || length == 0) {
            return -1;
        }
        
        int left = 0;
        int lack = 0;
        int start = 0;
        
        for (int i = 0; i < length; ++i) {
            left += gas[i] - cost[i];
            if (left < 0) {
                start = (i + 1) % length;
                lack += left;
                left = 0;
            }
        }
        
        return (lack + left >= 0) ? start : -1;
    }
};

时间复杂度:O(n), 遍历一次数组即可

空间复杂度:O(1), 没有利用额外的空间复杂度

leetcode_119. Pascal's Triangle II

题意

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

思路 & 实现

复杂一些的动态规划解决问题,动态规划公式依旧为result[j][index] = result[j - 1][index - 1] + result[j - 1][index]

如果采用空间复杂度为O(k)的算法的话,必须将上述的二维数组压缩为一维。但如果依旧采用从前到后的遍历方法的话,则会导致值覆盖的情况。根据上述描述,很容易想到从后向前遍历,这样就能保证前后两次的值不会因为遍历而被覆盖了。

如下是C++的实现方式。

class Solution {
public:
    vector<int> getRow(int rowIndex) {
        if (rowIndex < 0) {
            return vector<int>();
        }
        
        vector<int> result(rowIndex + 1, 1);
        
        for (int i = 1; i < rowIndex + 1; ++i) {
            for (int j = i - 1; j > 0; --j) {
                // 核心**,从后向前遍历,不会产生值覆盖的情况。
                result[j] = result[j] + result[j - 1];
            }
        }
        
        return result;
    }
};

时空复杂度

时间复杂度:O(n^2)。

空间复杂度:O(n)。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.