Code Caprice Training Camp day45| 70. Stair Climbing (Advanced) 322. Change Exchange 279. Complete Square

@TOC


foreword

Code Random Record Algorithm Training Camp day45


1. Leetcode 70. Climbing Stairs (Advanced)

1. Topic

Suppose you are climbing stairs. It takes n steps before you can reach the top of the building.

You can climb 1 or 2 steps at a time. How many different ways can you get to the top of the building?

Example 1:

Input: n = 2 Output: 2 Explanation: There are two ways to get to the top of the building. 1. 1st order + 1st order 2. 2nd order

Example 2:

Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top of the building. 1. Tier 1 + Tier 1 + Tier 1 2. Tier 1 + Tier 2 3. Tier 2 + Tier 1

hint:

1 <= n <= 45

Source: LeetCode Link: https://leetcode.cn/problems/climbing-stairs

2. Problem-solving ideas

Method 1: Dynamic Programming

ideas and algorithms

We use f(x)f(x) to represent the number of plans to climb to the xxth step, considering that the last step may have crossed one step or two steps, so we can list the following formula:

f(x)=f(x−1)+f(x−2)f(x)=f(x−1)+f(x−2)

It means that the number of ways to climb to the xxth step is the sum of the number of ways to climb to the x−1x−1 step and the number of ways to climb to the x−2x−2 step. It is easy to understand, because only 11 or 22 levels can be climbed each time, so f(x)f(x) can only be obtained from f(x−1)f(x−1) and f(x−2)f(x −2) Transfer over, and here to count the total number of solutions, we need to sum the contributions of these two items.

The above is the transition equation of dynamic programming, let's discuss the boundary conditions below. We started climbing from level 00, so from level 00 to level 00 we can see that there is only one solution, that is, f(0)=1f(0)=1; from level 00 to level 11 There is only one solution, that is, to climb one level, f(1)=1f(1)=1. These two as boundary conditions can continue to deduce the correct result of the nnth level backwards. We might as well write a few items to verify it. According to the transfer equation, f(2)=2f(2)=2, f(3)=3f(3)=3, f(4)=5f(4)=5,... ..., we enumerate these situations and find that the calculated result is correct.

It is not difficult for us to give an implementation with time complexity and space complexity of O(n)O(n) through transition equations and boundary conditions, but since f(x)f(x) here is only the same as f(x− 1) f(x−1) is related to f(x−2)f(x−2), so we can use the "rolling array idea" to optimize the space complexity to O(1)O(1). This implementation is given in the code below.

3. Code implementation

```java class Solution { public int climbStairs(int n) { int p = 0, q = 0, r = 1; for (int i = 1; i <= n; ++i) { p = q; q = r; r = p + q; } return r; } }

```

2. Leetcode 322. Change Exchange

1. Topic

You are given an integer array coins, denoting coins of different denominations, and an integer amount denoting the total amount.

Calculates and returns the minimum number of coins required to make up the total amount. Returns -1 if no combination of coins makes up the total amount.

You can consider the amount of each coin to be infinite.

Example 1:

Input: coins = [1, 2, 5], amount = 11 Output: 3 Explanation: 11 = 5 + 5 + 1

Example 2:

Input: coins = [2], amount = 3 Output: -1

Example 3:

Input: coins = [1], amount = 0 Output: 0

hint:

1 <= coins.length <= 12
1 <= coins[i] <= 231 - 1
0 <= amount <= 104

Source: LeetCode Link: https://leetcode.cn/problems/coin-change

2. Problem-solving ideas

Method 1: Memory search

Can we improve the exponential time complexity solution above? Of course, with dynamic programming, we can solve it in polynomial time. First, we define:

F(S)F(S):组成金额 SS 所需的最少硬币数量

[c0…cn−1][c0​…cn−1​] :可选的 nn 枚硬币面额值

We note that this problem has an optimal substructure property, which is the key to solving dynamic programming problems. An optimal solution can be constructed from the optimal solutions to its subproblems. How to decompose a problem into sub-problems? Suppose we know F(S)F(S), the number of coins that make up the least amount SS, and the face value of the last coin is CC. Then due to the optimal substructure of the problem, the transition equation should be:

F(S)=F(S−C)+1F(S)=F(S−C)+1

But we don't know the denomination of the last coin, so we need to enumerate each coin denomination c0,c1,c2…cn−1c0​,c1​,c2​…cn−1​ and choose the minimum value . The following recurrence relation holds:

F(S)=min⁡i=0...n−1F(S−ci)+1 subject to S−ci≥0F(S)=i=0...n−1min​F(S−ci​)+1 subject to S−ci​≥0

F(S)=0 ,when S=0F(S)=0 ,when S=0

F(S)=−1 ,when n=0F(S)=−1 ,when n=0

In the above recursion tree, we can see that many subproblems are evaluated multiple times. For example, F(1)F(1) is evaluated 1313 times. In order to avoid repeated calculations, we store the answer of each sub-question in an array for memorization. If the value of this question needs to be calculated next time, it can be directly retrieved from the array and returned, which can ensure that each sub-question can only be calculated at most once.

3. Code implementation

```java public class Solution { public int coinChange(int[] coins, int amount) { if (amount < 1) { return 0; } return coinChange(coins, amount, new int[amount]); }

private int coinChange(int[] coins, int rem, int[] count) {
    if (rem < 0) {
        return -1;
    }
    if (rem == 0) {
        return 0;
    }
    if (count[rem - 1] != 0) {
        return count[rem - 1];
    }
    int min = Integer.MAX_VALUE;
    for (int coin : coins) {
        int res = coinChange(coins, rem - coin, count);
        if (res >= 0 && res < min) {
            min = 1 + res;
        }
    }
    count[rem - 1] = (min == Integer.MAX_VALUE) ? -1 : min;
    return count[rem - 1];
}

}

```

3. Leetcode 279. Complete square number

1. Topic

Given an integer n, return the least number of perfect squares that sum to n.

A perfect square is an integer whose value is equal to the square of another integer; in other words, whose value is equal to the product of an integer multiplied by itself. For example, 1, 4, 9, and 16 are all perfect squares, but 3 and 11 are not.

Example 1:

Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4

Example 2:

Input: n = 13 Output: 2 Explanation: 13 = 4 + 9

hint:

1 <= n <= 104

Source: LeetCode Link: https://leetcode.cn/problems/perfect-squares

2. Problem-solving ideas

Method 1: Dynamic Programming

Ideas and Algorithms

We can write the state expression according to the requirements of the topic: f[i]f[i] represents the minimum number of squares required to represent the integer ii.

These numbers must fall in the interval [1,n][1,n

​]. We can enumerate these numbers, assuming that the current enumeration reaches jj, then we need to take the square of several numbers to form i−j2i−j2. At this point, we found that the sub-problem is similar to the original problem, but the scale has become smaller. This meets the requirements of dynamic programming, so we can write the state transition equation.

f[i]=1+min⁡j=1⌊i⌋f[i−j2]f[i]=1+j=1min⌊i

​⌋​f[i−j2]

Among them, f[0]=0f[0]=0 is the boundary condition. In fact, we cannot represent the number 00, just to ensure that jj encountered during the state transition is exactly ii

​ is legal.

At the same time, because the state needed to calculate f[i]f[i] is only f[i−j2]f[i−j2], which must be smaller than ii, so we only need to enumerate ii from small to large to calculate f [i]f[i] is enough.

3. Code implementation

```java class Solution { public int numSquares(int n) { int[] f = new int[n + 1]; for (int i = 1; i <= n; i++) { int minn = Integer.MAX_VALUE; for (int j = 1; j * j <= i; j++) { minn = Math.min(minn, f[i - j * j]); } f[i] = minn + 1; } return f[n]; } }

```

Guess you like

Origin blog.csdn.net/HHX_01/article/details/131285459