Data Structure and Algorithm Notes

Data Structures

1. Hash Table

we got a set of key-value pair(KVP), hash table use a hash function to search a certain position. Sacrifice space for time.

Hash table can reduce searching time efficiently, with an approximate O(1) time complexity

Hash Function:

// TODO

Algorithms

1. Dynamic Programming

The point is how we can abstract a dp table from an actual problem.

Key point: Optimization - optimal substrategy( iteration? ), unfollow-up effect, removal of redundancy, sacrifice space for time

case1 : A man can either go upstairs for one or to steps. Calculate how many ways there are to finish n steps.

   Just using is f(n) = f(n-1) + f(n - 2). 

case2 : Given a m-dimensional matrix, you can either move right or down starting from top left corner, ending up at bottom right corner. Find the minimal sum cost. The matrix is given as below:

1 3 5 9
8 1 3 4
5 0 6 1
8 8 4 0


denote an arbitary node as dp[i][j], 
where dp[0][0] = start point. 
dp[i][j] = min{dp[i - 1][j], dp[i][j - 1]} + cost[i][j].

case3 : Given an array, return the longest increasing subsequence.

if dp[i] > dp[i - 1]
    dp[i] = dp[i - 1] + 1 
else
    dp[i] = 1
end

case4 : Given 2 string, str1 and str2. Find the longest subsequence they share.

construnct a matrix dp[len1][len2]. 
dp[i][j] suggests the longest shared subsequence of str1(1: i), str(1 : j).

so dp[i][j] relates to dp[i-1][j], dp[i][j-1] and dp[i-1][j-1]

Use iteration to implement the algorithm

case5 : Backpack Problem

猜你喜欢

转载自blog.csdn.net/qq_37043191/article/details/79524508