0

我正在尝试逐字打印字符串“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];
}

}
4

1 回答 1

0

尝试这个。为我工作。希望这可以帮助

+ (void)printPermutations
{
    NSString *str = @"This Is Demo";
    NSArray *arr = [str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSMutableArray *permutationInput = [arr mutableCopy];
    [[self class] printPermutationOfString:permutationInput startIndex:0];
}

+(void)printPermutationOfString:(NSMutableArray*)arr startIndex:(int)startingindex
{
    if (startingindex == arr.count) {
        NSLog(@"%@",arr);
        return;
    }
    for (int i = startingindex; i < arr.count; i++) {
        [arr exchangeObjectAtIndex:startingindex withObjectAtIndex:i];
        [[self class] printPermutationOfString:arr startIndex:startingindex+1];
        if (i < (arr.count - 1))
            [[self class] reverse:arr start:startingindex+1 end:(startingindex+1)+(arr.count-startingindex-2)]; // edited here
    }
}
+ (void)reverse:(NSMutableArray *)arr start:(int)i end:(int)j {
    if ([arr count] == 0)
        return;
    while (i < j) {
        [arr exchangeObjectAtIndex:i
              withObjectAtIndex:j];
        i++;
        j--;
    }
}
于 2013-11-11T04:43:47.433 回答