ios 从数组中抽取m个元素组合

实现从n个元素的数组中抽取m个元素的生成的组合

- (void)printCombination{
    
    
//    NSArray *source = @[@0,@2,@4,@6,@8,@10,@12];
    NSArray *source = @[@0,@2,@4,@6];
    int m = 3;
    if (m > source.count) {
    
    
        NSLog(@"----source error ");
    }
    //从source中抽取m个数的生成的数组
    NSMutableArray *result = [self zuoheSource:source count:m total:m];
    NSLog(@"total:%ld,%@",result.count,result);
}
//从数组中抽取一定个数的元素组合
//@param count 当前在第几层,开始时count和total相等
//@param total 一共需要抽取几个数来做组合
- (NSMutableArray<NSMutableArray *> *)zuoheSource:(NSArray *)source count:(NSUInteger)count total:(NSUInteger)total{
    
    
    if (count == 0) {
    
    
        //没有了
        return nil;
    }
    NSMutableArray *tempArr = [NSMutableArray array];
    if (count == 1) {
    
    
        //最后一次
        for (NSNumber *aNum in source) {
    
    
            NSMutableArray *aRes = [NSMutableArray array];
            [aRes addObject:aNum];
            [tempArr addObject:aRes];
        }
        return tempArr;
    }
    //从头将每个可以独立的元素抽出
    for (int i = 0; i < source.count - count + 1; i++) {
    
    
        NSNumber *aNum = [source objectAtIndex:i];
        NSMutableArray *nextSource = [[NSMutableArray alloc] initWithArray:source];
        //继续抽取,
        [nextSource removeObjectsInRange:NSMakeRange(0, i+1)];
        NSMutableArray *nextRes = [self zuoheSource:nextSource count:count - 1 total:total];
        //组装结果
        for (NSMutableArray *aRes in nextRes) {
    
    
            [aRes addObject:aNum];
            [tempArr addObject:aRes];
        }
    }
    if (total == count) {
    
    
        //最外侧的结果
        return tempArr;
    }
    return tempArr;
}

猜你喜欢

转载自blog.csdn.net/mailddd/article/details/115315390

相关文章