[Learning Dynamic Programming] Robbery II (12)

Table of contents

How to learn dynamic programming?

1. Topic Analysis

2. Algorithm principle

1. Status representation

2. State transition equation

3. Initialization

4. Filling order

5. Return value

3. Code writing

Write at the end:


How to learn dynamic programming?

There is no shortcut to learning an algorithm, let alone learning dynamic programming,

Brush dynamic programming algorithm questions with me, and learn dynamic programming together!

1. Topic Analysis

Topic link: 213. Robbery II - Leetcode

 This topic is not difficult to understand,

There is only one difference between him and the first version of Dajiajieshe, that is, his end and end are connected.

All other conditions are the same.

Then we can actually analyze it, can we convert this question into the first version of the house robbery?

If we steal position 0, then position 1 cannot be stolen, and our position 2~n-2 can do whatever we want

If we don't steal position 0, then we can do whatever we want at position 1~n-1 (converted to looting I)

So the final returned value is the maximum value of these two cases.

2. Algorithm principle

1. Status representation

 f [ i ] means stealing nums[ i ] when stealing to position i, the maximum amount at this time

g [ i ] means that when stealing to position i, do not steal nums[ i ], the maximum amount at this time

2. State transition equation                

From our state representation, we can conclude that:

f [ i ] = g [ i - 1 ] + nums[ i ]

g [ i ] = max( f [ i - 1 ],g [ i - 1 ] )

3. Initialization

f [ 0 ] = num [ 0 ], g [ 0 ] = 0

4. Filling order

from left to right

5. Return value

max( f [ n - 1 ],g [ n - 1 ] )

3. Code writing

class Solution {
public:
    int rob(vector<int>& nums) {
        int n = nums.size();
        return max(nums[0] + rob1(nums, 2, n - 2) , rob1(nums, 1, n - 1));
    }
private:
    int rob1(const vector<int>& nums, int start, int n) {
        if(start > n) return 0;
        int size = nums.size();
        vector<int> f(size);
        auto g = f;
        f[start] = nums[start];
        for(int i = start + 1; i <= n; i++) {
            f[i] = g[i - 1] + nums[i];
            g[i] = max(f[i - 1], g[i - 1]);
        } 
        return max(f[n], g[n]);
    }
};

Write at the end:

The above is the content of this article, thank you for reading.

If you feel that you have gained something, you can give the blogger a like .

If there are omissions or mistakes in the content of the article, please private message the blogger or point it out in the comment area~

Guess you like

Origin blog.csdn.net/Locky136/article/details/131707267