Home >Java >javaTutorial >Introduction to the usage and algorithms of Java enumerations

Introduction to the usage and algorithms of Java enumerations

王林
王林forward
2023-04-23 08:19:06962browse

If you want to use the enumeration algorithm, you must firstdetermine the enumeration object, enumeration range and judgment conditions. Enumerate possible solutions one by one, verify whether each solution is the solution to the problem, and never miss any possible correct solution.

For example

One hundred dollars buys one hundred chickens Question: There is a person who has 100 yuan and plans to buy 100 chickens. When I went to the market, a large chicken cost three yuan, a small chicken costed three yuan, and a medium-sized chicken cost two yuan. Now, please write a program to help him plan how to buy 100 chickens for exactly 100 yuan?

We can set the rooster as x, the hen as y, and the chick as z, and we can get the following equation: After exhaustively enumerating the value of each rooster, the value of the hen and the chick can be expressed by the x of the rooster.

Code:

Introduction to the usage and algorithms of Java enumerationsThe code in the picture uses three times of for loop time complexity (if you don’t know, don’t worry, there will be a special article to discuss it later) for O (N^3); We all like a program that is simple, does not consume space, is short and concise, and looks high-end. Optimization is introduced below.

Optimization routine

Although enumeration is a A very profitable algorithm, but you can still improve the efficiency of problem solving

by narrowing the enumeration range. Also avoid repeated enumeration. Let’s look at the second way:

x y z = 100 ①

5x 3y z/3 = 100 ②

Let ②x3-① It can be obtained

7x 4y = 100

=>y = 25-(7/4)x ③

And because 0

x = 4k ④

Substitute ④ into ③ to get

=> y = 25-7k ⑤

Substitute ④⑤ into ① It can be seen that

=> z = 75 3k ⑥

To ensure that 0

Code:


Introduction to the usage and algorithms of Java enumerationsThis code has reached the basis of a layer of loops, and the time complexity is O(n);

This chestnut introduces a method of enumeration optimization that is to reduce the variables of the enumeration. The entire routine of optimizing enumeration mainly has two aspects: one is to reduce enumeration variables, and the other is to reduce the scope of enumeration.

The above is the detailed content of Introduction to the usage and algorithms of Java enumerations. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete