版权声明:本文为博主原创文章,未经博主允许不得转载。
需递归求解
OC版源码:
#import "ViewController.h"
static NSMutableArray *ComputeAllCombinationsWithArrays(NSMutableArray *arrays){
NSInteger len = arrays.count;
if (len >= 2) {
NSInteger len1 = [arrays[0] count];
NSInteger len2 = [arrays[1] count];
NSInteger lenBoth = len1 * len2;
NSMutableArray *temp = [NSMutableArray arrayWithCapacity:lenBoth];
for (int i = 0; i < len1; i ++) {
for (int j = 0; j < len2; j ++) {
if ([[arrays[0] objectAtIndex:i] isKindOfClass:[NSArray class]]) {
NSMutableArray *join = [NSMutableArray arrayWithArray:[arrays[0] objectAtIndex:i]];
[join addObject:[arrays[1] objectAtIndex:j]];
[temp addObject:join];
}else{
[temp addObject:[NSArray arrayWithObjects:[arrays[0] objectAtIndex:i], [arrays[1] objectAtIndex:j],nil]];
}
}
}
NSMutableArray *newArr = [NSMutableArray arrayWithCapacity:len - 1];
[newArr addObject:temp];
for (int i = 2; i < arrays.count; i ++) {
[newArr addObject:arrays[i]];
}
return ComputeAllCombinationsWithArrays(newArr);
}else{
return arrays[0];
}
}
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"%@",ComputeAllCombinationsWithArrays(@[@[@"1",@"2"],@[@"3",@"4"],@[@"5",@"6"],@[@"7",@"8",@"9"]].mutableCopy));
}
@end
结果为:
(1,3,5,7),
(1,3,5,8),
...
网友评论