全排列
#import <Foundation/Foundation.h>
@interface Permutation : NSObject
- (void)permutation:(NSString*)str;
@end
#import "Permutation.h"
@implementation Permutation
static int i = 0;
- (void)perm:(NSMutableString*)sofar andRest:(NSMutableString*)rest{
for (int i = 0; i < (int)rest.length; i++) {
NSMutableString *next = [NSMutableString stringWithString:sofar];
NSMutableString *remaing = [NSMutableString stringWithString:rest];
[next appendString:[rest substringWithRange:NSMakeRange(i, 1)]];
[remaing deleteCharactersInRange:NSMakeRange(i, 1)];
[self perm:next andRest:remaing];
}
if ([rest isEqual:@""]) {
NSLog(@"%@", sofar);
i++;
}
}
- (void)permutation:(NSString*)str{
NSMutableString *str1 = [NSMutableString string];
NSMutableString *str2 = [NSMutableString stringWithFormat:@"%@", str];
[self perm:str1 andRest:str2];
NSLog(@"%d", i);
}
@end
#import "Permutation.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
/*
全排列 abcd
*/
Test *test = [[Test alloc] init];
[test permutation:@"abc"];
}
return 0;
}
网友评论