排列算法

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _array = @[@"0", @"1", @"2", @"3", @"4", @"5", @"6", @"7"];
    _total = [_array count];
    _sum = 0;
    
    NSInteger count = [_array count];
    for (int i = 0; i < count; i++) {
        for (int j= 0; j < count; j++) {
            for (int k = 0; k < count; k++) {
                if (!(i == j || j == k || i == k)) {
//                    NSLog(@"%@, %@, %@", array[i], array[j], array[k]);
                }
            }
        }
    }
    
    NSMutableArray *nullArray = [NSMutableArray array];
    for (int i = 0; i < _total; i++) {
        [nullArray addObject:@"-1"];
    }
    
    [self list:nullArray order:0];
    printf("%ld\n", _sum);
    
    
    
}

- (void)list:(NSMutableArray *)array order:(int)order{
    array = [array mutableCopy];
    
    if (order == _total) {
        for (NSString *s in array) {
            int a = [s intValue];
            printf("%d, ", [[_array objectAtIndex:a] intValue]);
        }
        _sum++;
        printf("\n");
    } else {
        for (int i = 0; i < _total; i++) {
            
            if ([array containsObject:[NSString stringWithFormat:@"%d", i]]) {
                //不允许有重复的
                continue;
            }
            
            [array replaceObjectAtIndex:order withObject:[NSString stringWithFormat:@"%d", i]];
            [self list:array order:order+1];
        }
    }
    
}

展开阅读全文

没有更多推荐了,返回首页