Example of a factorial time algorithm O( n! )

前端 未结 4 718
情深已故
情深已故 2020-12-08 06:36

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

4条回答
  •  爱一瞬间的悲伤
    2020-12-08 07:10

    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!
    

提交回复
热议问题