全排列

全排列

#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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容