Question 96. Unique Binary Search Trees

The description of the question is in the following link:

 

My code:

class Solution:
    def numTrees(self, n: int) -> int:
        if n ==1:
            return 1
        elif n ==2 :
            return 2
        else:
            TotalNumberList = [1]*(1+n)
            for Length in range(2,n+1):
                TotalSum = 0
                for Index in range(Length):
                    NumberDevideByThisIndex = TotalNumberList[Index]*TotalNumberList[Length-1-Index]
                    TotalSum += NumberDevideByThisIndex
                TotalNumberList[Length] = TotalSum
            return TotalNumberList[n]

Explanation: It actually does not matter if the value is from 1 to n or otherwise, as long as they are sorted by some order. The logic is that for each particular value we choose, the list is divided into two parts: left list and right list. We just need to multiply the number in the left list and right list to get the total number of trees we have for this particular number. As for all the ordered list with the same length, they all have the same number of trees, hence we just need to start from the number of trees with one and zero, then gradually calculate from one to n and return the nth one in the list.

Question 91 Decode Ways

Question:

https://leetcode.com/problems/decode-ways/

 

My code

class Solution:
    def numDecodings(self, s: str) -> int:
# First we finish the part that the length of the string is 1
        if len(s) ==1:
            if int(s[0])== 0:
                return 0
            else:
                return 1
        else: # we then finish the part which has length larger than 1
            if int(s[0]) == 0:
                Mat = [0]*len(s)
            else:
                Mat = [1]*len(s)
            for StringNum in range(1,len(s)):
                if int(s[StringNum-1]) == 0:
                    if int(s[StringNum]) == 0:
                        Mat[StringNum] = 0
                    else:
                        if StringNum ==1:
                            Mat[StringNum]= 0
                        else:
                            Mat[StringNum] = Mat[StringNum-1] 
                elif int(s[StringNum-1])==1:
                    if int(s[StringNum])==0:
                        if StringNum == 1:
                            Mat[StringNum] = 1
                        else:
                            Mat[StringNum] = Mat[StringNum-2]
                    else:
                        if StringNum ==1:
                            Mat[StringNum] = 2
                        else:
                            Mat[StringNum] = Mat[StringNum-1]+Mat[StringNum-2]
                elif int(s[StringNum-1]) ==2:
                    if int(s[StringNum]) == 0:
                        if StringNum ==1:
                            Mat[StringNum] = 1
                        else:
                            Mat[StringNum] = Mat[StringNum-2]
                    elif int(s[StringNum]) >=7:
                        if StringNum ==1:
                            Mat[StringNum] =1
                        else:
                            Mat[StringNum] = Mat[StringNum-1]
                    else:
                        if StringNum ==1:
                            Mat[StringNum] = 2
                        else:
                            Mat[StringNum] = Mat[StringNum-1]+ Mat[StringNum-2]
                else:
                    if int(s[StringNum]) == 0:
                        Mat[StringNum] = 0
                    else:
                        if StringNum == 1:
                            Mat[StringNum] = 1
                        else:
                            Mat[StringNum] = Mat[StringNum-1]
        
        return Mat[len(s)-1]

Explanation:

The Structure of the code is a little difficult to explain in words. There will be (If I do not forget) a full chart to illustrate the whole idea.

Question 70 Climbing Stairs

The description of the question is in the following link:

https://leetcode.com/problems/climbing-stairs/

My Code:

class Solution:
    def climbStairs(self, n: int) -> int:
        Ladder = [1]*n;
        if n ==1: 
            return 1;
        else:
            Ladder[1] = 2;
            for LadNum in range(2,n):
                Ladder[LadNum] = Ladder[LadNum-1]+Ladder[LadNum -2]
            return Ladder[n-1]

Explanation:

The idea is clear: the only way to reach the nth ladder is that going from n-1th ladder with 1 step and n-2th ladder with 2 steps. So we just need to sum the number of steps to reach these two ladders to get the step to reach nth ladder. Just need to be very careful about some special situation and initialisation.

 

Question 64 minimum sum path

The description of the question is included in the following link:

https://leetcode.com/problems/minimum-path-sum/

My Code

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        RowNum = len(grid);
        ColNum = len(grid[0]);
        Mat = [[0]*ColNum for _ in range(RowNum)];
        Mat[0][0] = grid[0][0];
        for row in range(RowNum):
            if row == 0:
                for col in range(1,ColNum):
                    Mat[row][col] = grid[row][col]+ Mat[row][col-1];
            else:
                for col in range(ColNum):
                    if col ==0 :
                        Mat[row][col] = grid[row][col]+Mat[row-1][col];
                    else:
                        Mat[row][col] = min(Mat[row][col-1],Mat[row-1][col])+ grid[row][col];
        return Mat[RowNum-1][ColNum-1];

Explanation:

The idea behind the code is really simple. For each block, there are two ways to go in: from the top or from left block. We then just need to find the minimum value between these two then add the number in the block to have the minimum value that can go to that block. So we keep this procedure and then we may find the minimum value of the block we want.

Question 63 Unique Paths 2

The description of the question is in the following link:

https://leetcode.com/problems/unique-paths-ii/

My code:

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        Mat = [[1]*len(obstacleGrid[0]) for _ in range(len(obstacleGrid))];
        
        for row in range(len(obstacleGrid)):
            if row == 0 :
                for col in range(len(obstacleGrid[0])):

                        if obstacleGrid[row][col] ==1:
                            Mat[row][col] =0;
                        else:
                            Mat[row][col] = Mat[row][col-1];

            else:
                for col in range(len(obstacleGrid[0])):
                    if col == 0:
                        if obstacleGrid[row][col] == 1:
                            Mat[row][col] = 0;
                        else:
                            Mat[row][col] = Mat[row-1][col];
                    else:
                        if obstacleGrid[row][col] == 1:
                            Mat[row][col] = 0;
                        else:
                            Mat[row][col] = Mat[row][col-1]+Mat[row-1][col];
        return Mat[len(obstacleGrid)-1][len(obstacleGrid[0])-1];

Explanation: This part of the code is very similar to the previous part. Except that we need to be very careful about the situation that whenever there is a rock, we need to set the path number at that part as 0. I start from row 0 because there might be an obstacle on the row 0 or col 0, so we need to take this into consideration.

Question 62 Unique Path

The description of the question is in the following link:

My Code:

    def uniquePaths(self, m: int, n: int) -> int:
        Mat = [[1] * n for _ in range(m)]

        for col in range(1, m):
            for row in range(1, n):
                Mat[col][row] = Mat[col - 1][row] + Mat[col][row - 1];

        return d[m - 1][n - 1];

Explain: Starting From the very beginning and go one by one. Each step is generated from the sum of the step number above it and left to it.

 

Question 53 Maximum Subarray

The description of the question can be found in the following link:

https://leetcode.com/problems/maximum-subarray/

My Code:

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        List1 = [];
        Maximum = -2**31+1;
        for i in range(len(nums)):
            List1.append(nums[i]);
            Maximum= max(sum(List1), Maximum)
            if(sum(List1) < 0): 
                List1 = [];
        return(Maximum);

Explain: Keep going until first get a negative summation. Then we start a new array from the next element.

Question 8 String to Integer

The description of the question is in the following link:

https://leetcode.com/problems/string-to-integer-atoi/

My Code:

    def myAtoi(self, String) -> int:
        if(String == ""):
            return(0);
        else:
            while(String[0] == " "):
                String = String[1:len(String)];
                if(String == ""):
                    return(0);
            sign = 1;
            if(String[0] == "-"):
                sign = -1;
                String = String[1:len(String)];
            else:
                if(String[0] == "+"):
                    String = String[1:len(String)];
            Number = ""
            i = 0;
            while(i 2**31-1):
                    return(2**31-1);
                else:
                    if(Number < -2**31):
                        return(-2**31);
                    else: 
                        return(Number);

Explanation:

The idea is clear. First part is to discard all the possible space. What we need to be very careful is the empty string. The second part is to determine if there is any potential sign for the number. The last part is to take all the available number string and then do the conversion.

Question 7 Reverse Integer

The description of the code is included in the following link.

class Solution:
    def reverse(self, x: int) -> int:
        if(x>=0):
            z = int(str(x)[::-1]);
            if (z>(2**31-1) ):
                return(0);
            else:
                return(z);
                
        else:
            z = abs(x);
            z = int(str(z)[::-1]);
            z = -z;
            if (z<-2**31):
                return(0);
            else:
                return(z);

Explain:

Turn integer into string and then take reverse of the string and then turn it back. Only thing that needs to be careful is if it exceeds the range proposed in the question.

 

Question 6 ZigZag Conversion

The description of the question can be found in the following link:

https://leetcode.com/problems/zigzag-conversion/submissions/

  1. My Code;

微信图片_20200312024858

Explain: The idea is quite clear. For each character in the string, find out which line does is belong to. As we go through the string from left to right and it is exactly the order required in the zigzag conversion, hence we do not need to worry too much about the order of the conversion. We use a dictionary to store the character in each row, and then we put all of them together at the same time in the end. One special case is when the required row number is one, in this case we just need to return the original string.