蛮力写算法
Brute Force Algorithms are exactly what they sound like – straightforward methods of solving a problem that rely on sheer computing power and trying every possibility rather than advanced techniques to improve efficiency.
蛮力算法听起来确实像是–解决问题的直接方法,该方法依赖于纯粹的计算能力,并尝试各种可能性而不是先进的技术来提高效率。
For example, imagine you have a small padlock with 4 digits, each from 0-9. You forgot your combination, but you don't want to buy another padlock. Since you can't remember any of the digits, you have to use a brute force method to open the lock.
例如,假设您有一个带有4位数字的小挂锁,每个数字从0-9。 您忘记了密码,但是您不想再购买一个挂锁。 由于您不记得任何数字,因此必须使用蛮力方法来打开锁。
So you set all the numbers back to 0 and try them one by one: 0001, 0002, 0003, and so on until it opens. In the worst case scenario, it would take 104, or 10,000 tries to find your combination.
因此,您将所有数字都设置回0,然后一一尝试:0001、0002、0003,依此类推,直到打开为止。 在最坏的情况下,将需要10 4或10,000次尝试来找到您的组合。
A classic example in computer science is the traveling salesman problem (TSP). Suppose a salesman needs to visit 10 cities across the country. How does one determine the order in which those cities should be visited such that the total distance traveled is minimized?
计算机科学中的经典示例是旅行商问题(TSP)。 假设业务员需要访问全国10个城市。 如何确定应该访问这些城市的顺序,以使旅行的总距离最小化?
The brute force solution is simply to calculate the total distance for every possible route and then select the shortest one. This is not particularly efficient because it is possible to eliminate many possible routes through clever algorithms.
蛮力解决方案仅是计算每种可能路线的总距离,然后选择最短的路线。 这不是特别有效,因为可以通过巧妙的算法消除许多可能的路线。
The time complexity of brute force is O(mn), which is sometimes written as O(n*m) . So, if we were to search for