Example of a factorial time algorithm O( n! )

耗尽温柔 提交于 2019-11-27 20:39:24

问题


I'm studying time complexity in school and our main focus seems to be on polynomial time O(n^c) algorithms and quasi-linear time O(nlog(n)) algorithms with the occasional exponential time O(c^n) algorithm as an example of run-time perspective. However, dealing with larger time complexities was never covered.

I would like to see an example problem with an algorithmic solution that runs in factorial time O(n!). The algorithm may be a naive approach to solve a problem but cannot be artificially bloated to run in factorial time.

Extra street-cred if the factorial time algorithm is the best known algorithm to solve the problem.


回答1:


Generate all the permutations of a list

You have n! lists, so you cannot achieve better efficiency than O(n!).




回答2:


Traveling Salesman has a naive solution that's O(n!), but it has a dynamic programming solution that's O(n^2 * 2^n)




回答3:


List all permutations of an array is O(n!). Below is a recursive implementation using the swap method. The recursion is inside the for loop and the elements in the array are swapped in position until no more elements remain. As you can see from the result count, the number of elements in the array is n!. Each permutation is an operation and there are n! operations.

def permutation(array, start, result)
    if (start == array.length) then
        result << array.dup  
    end
    for i in start..array.length-1 do
        array[start], array[i] = array[i], array[start]
        permutation(array, start+1,result)
        array[start], array[i] = array[i], array[start]
    end 
    result   
end        


p permutation([1,2,3], 0, []).count  #> 6 = 3!
p permutation([1,2,3,4], 0, []).count #> 24 = 4!
p permutation([1,2,3,4,5], 0, []).count #> 120 = 5!



回答4:


Here is a simple example with Big O( n! ):

This is in python 3.4

 def factorial(n):
    for each in range(n):
        print(n)
        factorial(n-1)


来源:https://stackoverflow.com/questions/16555978/example-of-a-factorial-time-algorithm-o-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!