我正在尝试逐字打印字符串“This Is Demo”的所有排列。例如,有效的排列将是“This Demo Is”、“Demo Is This”、“Demo This is”。我的程序没有打印所有排列。代码有什么问题?
+(void)printPermutations
{
NSString *str = @"This Is Demo";
NSArray *arr = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray *permutationInput = [arr mutableCopy];
[[self class] printPermutationOfString:permutationInput startIndex:0 endIndex:arr.count-1];
}
+(void)printPermutationOfString:(NSMutableArray*)arr startIndex:(int)startingindex
endIndex:(int)endIndex
{
if (startingindex == endIndex) {
NSLog(@"%@",arr);
return;
}
for (int i = startingindex; i < endIndex; i++) {
[arr exchangeObjectAtIndex:startingindex withObjectAtIndex:i];
[[self class] printPermutationOfString:arr startIndex:i+1 endIndex:endIndex];
[arr exchangeObjectAtIndex:startingindex withObjectAtIndex:endIndex];
}
}