本文共 1432 字,大约阅读时间需要 4 分钟。
@interface StringPermutations : NSObject - (void)permuteString:(NSString *)inputString; @end #import "StringPermutations.h" @implementation StringPermutations - (void)permuteString:(NSString *)inputString { NSString *chars = inputString; NSArray *charArray = [chars componentsSeparatedByString: @""]; if (charArray.count <= 1) { NSLog(@"排列结果:%@", inputString); return; } NSMutableString *result = [NSMutableString string]; void permute(NSArray *array, NSUInteger index, NSString *currentString, NSMutableArray *used, NSString *resultString) { if (index == array.count) { [resultString appendFormat: @"'%@'", currentString]; [result appendString: resultString]; [resultString reset]; return; } for (NSUInteger i = 0; i < array.count; i++) { if (![(NSNumber *)[array objectAtIndex:i] boolValue]) { [permute array: array, index: i+1, currentString: [currentString appendFormat: @"'%c'", [array[i] characterAtIndex: 0]], used: used, resultString: resultString); } } [resultString reset]; } NSMutableArray *used = [NSMutableArray array]; [permute charArray, 0, @"", used, result]; for (NSString *str in [result componentsSeparatedByString: @"\n"]) { NSLog(@"排列结果:%@", str); } } @end 转载地址:http://kxifk.baihongyu.com/