### Dynamic programming algorithm

# 1. Goal

It is the process of solving the optimization process of the decision-making process.

# 2. Method

Decomposing the original problem into sub-problems for solution is the idea of divide and conquer.

# 3. Process

There are four main steps:

- Divide sub-problems: break a big problem into small problems
- Status: How to deal with minor issues.
- State transition: that is, how the parent problem derives the child problem.
- Determine the boundary: determine what the initial state is? The smallest sub-problem? What is the final state?

# 4. Examples

## (1) Likou: 5. The longest palindrome substring

```
class Solution {
public:
string longestPalindrome(string s) {
int length = s.length();
vector<vector<bool>> answer(length, vector<bool>(length));
int Start = 0,End = 0;
//自己与自己的关系全部设为true，也就是只有一个的情况
for(int i = 0;i < length;i++){
answer[i][i] = true;
}
//开始进行遍历，达到条件的就改成true
for(int j = 1;j < length;j++){
for(int i = 0;i < j;i++){
if(s.at(i) == s.at(j) &&(i+1 == j || answer[i+1][j-1]))
{
if(j - i >= End - Start){
Start = i;
End = j;
}
answer[i][j] = true;
}
}
}
return s.substr(Start,(End - Start + 1));
}
};
```

ps: I encountered a lot of problems when I was writing this part of the questions, and it was very difficult to do it, alas.

## (1) Likou: 1018. Binary prefix divisible by 5

For example, [0,1,1,1], the first number is 0, the second number is 01, the third is 011, and the fourth is 0111, converted to decimal, which are 0, 1, 3 , 7. Then according to the binary rule, each time the data moves one bit to the left, the data size is multiplied by 2.

Then you can use sum = 0, sum = sum *2 + num. num is the element in [0,1,1,1], and sum is the converted decimal.

```
class Solution {
public:
vector<bool> prefixesDivBy5(vector<int>& A) {
vector<bool> a;
int sum = 0;
for(auto num : A){
sum = sum * 2 +num;
cout<<sum % 5<<endl;
if(sum % 5 == 0) a.push_back(1);
else if(sum % 5 != 0 ) a.push_back(0);
}
return a;
}
};
```

Then the operation timed out, so I am going to transform it.

First, we can transform sum*2 into sum<<1, directly change it to the binary moving position, and then make sum equal to the remainder left by the previous sum.

```
class Solution {
public:
vector<bool> prefixesDivBy5(vector<int>& A) {
vector<bool> a;
int sum = 0;
for(auto num : A){
sum = (sum << 1) +num;
a.push_back(sum % 5 == 0);
}
return a;
}
};
```

Then it reported that the storage space of the int type data is not enough, then find a way to make the int store smaller.

```
class Solution {
public:
vector<bool> prefixesDivBy5(vector<int>& A) {
vector<bool> a;
int sum = 0;
for(auto num : A){
sum = ((sum << 1) +num) %5;
a.push_back(sum == 0);
}
return a;
}
};
```

Every time sum is divided by 5 so that sum is only equal to his remainder, because the extra number is also a multiple of five, the key is to see how the remaining part of the data can be processed.