Reputation: 675
I have the following code to print permutations of a given string. [For simplicity and not to loose focus on what I am trying, lets assume there are not duplicates characters in the string]
public static int count = 0;
public static void permute(String soFar, String strLeft) {
if(strLeft.length() == 1) {
soFar += strLeft;
System.out.println(++count + " :: " + soFar);
}
for(int i=0; i<strLeft.length(); i++) {
permute(soFar + strLeft.charAt(i), strLeft.substring(0,i) + strLeft.substring(i+1));
}
}
/**
* @param args
*/
public static void main(String[] args) {
String input = "abcd";
permute("",input);
}
I am trying to figure out the running time of this code.
My chain of thoughts so far: Trying to write a recurrence,
T(n) = n * T(n-1) + O(n) for n > 1
= 1 for n = 1
There are n! permutations, but the number of recursive calls are greater than n!. In-fact for the example where input string is "abcd" , i.e. 4 characters, the number of calls to the permute function is 65.
Any pointers on how I should go about finding the running time of this code?
Upvotes: 0
Views: 1234
Reputation: 4622
Well, first of all, you make redundant calls. If there is only one character left, you emit a solution. But then you will still call permute
with an empty string and spoils the calling count.
My first improvement would be to add an else
to the if
clause.
public static void permute(String soFar, String strLeft) {
if(strLeft.length() == 1) {
soFar += strLeft;
System.out.println(++count + " :: " + soFar);
}
else {
for(int i=0; i<strLeft.length(); i++) {
permute(soFar + strLeft.charAt(i), strLeft.substring(0,i) + strLeft.substring(i+1));
}
}
}
This cuts down the amount of calls to 41. And to count the number of calls, construct the calling tree and count the nodes. As each call is done by removing one character from the string, there are:
1 calls of length 4,
4 calls of length 3,
12 calls of length 2 and
24 calls of length 1
Which sums up to 41. Voilá.
Upvotes: 2