Definition:
If we use the definition to calculate the sequence, the time complexity will be
def fib(n) :
if n == 0 or n == 1 :
return 1
else :
return fib(n-1) + fib(n-2)
“Memorization”: We can memorize the computed value to improve the time complexity : .
def _fib(n) :
if n == 0 or n == 1 :
return 1
else :
return fib(n-1) + fib(n-2)
checked = dict()
def fib(n) :
if n not in checked :
checked[n] = _fib(n)
return checked[n]
Example
abcsequence
and xsequenyce
is sequence
. (Note that the sequence does not need to be continuous; only the order matters)Algorithm
We can maintain a function with two parameter , the longest common subsequence if we only consider the first characters in the first string and the first characters in the second.
If we want to find the longest common subsequences of aaabbab
and babaaba
, then we need to find .
if the string at 6 is different, or if not
Similar problem: Edit distance. We can see it as an generalization.
Example
1 << 3 == 8
, since 1000 in binary is 8. (bit-wise left-shifting)5|6 == 7
, since the bit-wise OR of 101 and 110 is 111XOR
, NOT
, etc.Why Bit-wise?
Suppose you have three locations, given the distance between locations. You want to visit any single location (with arbitrary starting and ending location) while keeping the distance minimum.
If we use a brute force algorithm, the time complexity will be
The infomation to track is where I am, and where I’ve been to (complement to where I need to go)
We will maintain a table dp
with rows of location and columns of bit masks, where dp[i][j]
represents the minimum amount of distance we still need to travel.
We already know that the last column is all 0, since we have visited all the locations. Then we can calculate the table backwards (ignoring invalid states). dp = 0
(2, 100) can go to (1, 110) or (0, 101). What do I do? It is better to go to (0, 101) since the total cost is smaller.
There are entries in the table, and operations need to compute each entry. So the overall time complexity is
Note: If the set has more than 30 items, don’t use int
. If the set has more than 60 items, don’t use long
.