【LeetCode】Sword Pointer Offer <Second brush>(7)

Table of contents

Topic: Sword Pointer Offer 14- I. Cut the Rope - LeetCode

Question interface:

Problem-solving ideas:

Code:

Passed! ! !

Topic: Sword Pointer Offer 14- II. Cut the Rope II - LeetCode

Question interface:

Problem-solving ideas:

Code:

Passed! ! !

Write at the end:


Topic: Sword Pointer Offer 14- I. Cut the Rope - LeetCode

Question interface:

func cuttingRope(n int) int {

}

Problem-solving ideas:

I think of two methods for this question, one is to use dynamic programming, the other is to use mathematical laws to do it, but I am not good at mathematics, so I use dynamic programming to do this question:

The core of dynamic programming is actually its state transition equation. Here I will talk about how to obtain the state transition equation of this question: First, because if subtracting 1 grid, it will not help the overall product, so we will Starting from 2(j)

Then, if it can be cut, there are two cases, one is to cut, the other is not to cut: 1) If cut, then the product sum is j * ( ij ) , 2) If not cut, then the product sum is j * dp[ ij ], so we only need to ask for their maximum value.

In this way, we have obtained the state transition equation, and we can write code:

Code:

func cuttingRope(n int) int {
    dp := make([]int, n+1)
    dp[2] = 1
    for i := 3; i < n + 1; i++ {
        for j := 2; j < i; j++ {
            dp[i] = max(dp[i], max(j * (i-j), j * dp[i-j]))
        }
    }
    return dp[n]
}

func max(x, y int) int {
    if x > y {
        return x
    }
    return y
}

Passed! ! !

Title: Sword Pointing to Offer 14- II. Cutting the Rope II - LeetCode

Question interface:

func cuttingRope(n int) int {

}

Problem-solving ideas:

This question is actually exactly the same as the one above, but this question is very fucked up. It must be done with mathematical laws, because it puts the numbers so large that we cannot use dynamic programming to solve it.

So we have to use greed to solve it. I can't deduce this mathematical law, but I will directly use the conclusion, that is, the closer the rope is cut to 3, the greater the final value, so we only need to cut enough 3. , so the code is easy to write.

Code:

func cuttingRope(n int) int {
    if n == 2 {return 1}
    if n == 3 {return 2}
    if n == 4 {return 4}
    ret := 1
    for n > 4 {
        n -= 3
        ret = ret * 3 % (1e9 + 7)
    }
    ret = ret * n % (1e9 + 7)
    return ret
}

Passed! ! !

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/132664323