简体   繁体   中英

What is the time complexity of the code (generating permutations)

Please see the code at the link below: https://stackoverflow.com/a/20614037/1676147

My thoughts:

Time complexity here would depend on two factors: 1) Number of recursive calls: O(n) where n is the number of characters in the original input string

2) The work involved in the two for loops: O(n!)?

Basically, the first for loop is iterating each string in the set 'permSet' The number of permutations for an n-character string can be n!. Thus, this set would contain n! strings. Correct?

The second for loop places one character (variable 'a' in the code) at each of the potential positions in each of these strings.

I am confused at this step.

Your analysis is correct. For a string of length N , you have N-1 recursions, with string length of M , one each for lengths 1 through N-1 . Each recursion deals with a list of size (M-1)!, and inserts the next character at each of M positions (0 through M-1).

Each call has time M * (M-1)!, or M! Sum these over M = 1 to N.

1! + 2! + 3! + ... + N!

This sum is O(n!) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM