指数时间复杂度的真实示例
我正在寻找一个直观的、现实世界的问题示例,该问题需要(最坏情况)指数时间复杂度来解决我正在做的演讲。
以下是我提出的其他时间复杂度的示例(其中许多取自 这个问题):
- O(1) - 确定一个数字是奇数还是偶数
- O(log N) - 在字典中查找一个单词(使用二分搜索)
- O(N) - 读一本书
- O(N log N) - 对一副扑克牌进行排序(使用合并排序)
- O(N^2) - 检查购物车中是否有购物清单上的所有物品
- O(infinity) -抛硬币直到正面朝上
有什么想法吗?
I'm looking for an intuitive, real-world example of a problem that takes (worst case) exponential time complexity to solve for a talk I am giving.
Here are examples for other time complexities I have come up with (many of them taken from this SO question):
- O(1) - determining if a number is odd or even
- O(log N) - finding a word in the dictionary (using binary search)
- O(N) - reading a book
- O(N log N) - sorting a deck of playing cards (using merge sort)
- O(N^2) - checking if you have everything on your shopping list in your trolley
- O(infinity) - tossing a coin until it lands on heads
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
ps 为什么你的最后一个例子的复杂度是 O(infinity) ?这是线性搜索 O(N) .. 世界上的人口不到 70 亿。p.s. why is your last example is of complexity O(infinity) ? it's linear search O(N) .. there are less than 7 billion people in the world.披萨餐厅有多种配料可供选择,包括
顾客可以为披萨选择任何配料组合,也可以不选择任何配料。现在考虑一种算法,该算法可以找到每种可能的独特配料组合。这是一个时间复杂度为 O(2^n) 的指数算法。
看看当您向菜单中添加新的配料时,可能的组合如何(呈指数级)增长:
因此,只需 20 种配料,就有超过 100 万种可能的组合!
A pizza restaurant has several toppings to choose from
Customers may choose any combination of toppings or none at all for their pizza. Now consider an algorithm that finds every possible unique combination of toppings. This is an exponential algorithm with time complexity O(2^n).
Look how the possible combinations grow (exponentially) when you add a new topping to the menu:
So with just 20 types of toppings, there are over 1 million possible combinations!
一个暴力且幼稚的 n 皇后问题的解决方案。
你必须将 n 个皇后放在一个*n 个棋盘上,而不让它们被其他人拿走。
虽然有未尝试过的配置,
转到下一个解决方案并
测试一下
假设每个皇后都在给定的行上,则放置该皇后的可能性有 n 种,放置其他 (n-1) 个皇后的可能性也有 n 种(因为不检查重复的行)。
因此,你的复杂度是 O(n^n)
A brute-force and naive n-queens problem's solution.
You have to place n queens on a n*n board without them to be taken by others.
while there are untried configs,
go to next solution and
test it
Assuming every queen is on a given row, there are n possibilities for the queen to be placed and n for the (n-1) other queens (because duplicate rows are not checked).
Therefore, you've got a O(n^n) complexity
旅行商问题的强力解决方案是 O(n!),大约为 O(N^N)
The brute force solution of the traveling salesman problem is O(n!) which is approximately O(N^N)
如何在集合中找到整数的子集,使其总和为指定值 X?
我相信这有复杂度 O(2^(n/2))
What about finding a subset of integers within a set such that their sum is a designated value X?
I believe this has complexity O(2^(n/2))