类似于背包问题,前提条件是数组全是正整数和0,先求和Sum,再从子数组中找出接近Sum/2的子数组
@interface TempState : NSObject @property (nonatomic,assign) int iIdx; @property (nonatomic,assign) int jIdx; @end @implementation TempState @end
- (void)getSubArryMinABS{ // 输入 NSMutableArray *inputArry = [NSMutableArray arrayWithObjects:@"2",@"4",@"5",@"6",@"7" ,nil]; NSLog(@"inputArry:%@",inputArry); // 输出 NSMutableArray *outputArry = [NSMutableArray arrayWithCapacity:10]; // 保存对应i,j数组元素的istrue状态 NSMutableArray<TempState *> *tempStateArry = [NSMutableArray<TempState *> arrayWithCapacity:10]; // 可根据实际情况扩容,如果做成通用,建议取count*1000,防止越界错误 NSMutableArray *dpArry = [NSMutableArray arrayWithCapacity:20]; for (int i = 0; i< 20; i++) { [dpArry addObject:@"0"]; } __block NSInteger orginSum = 0; [inputArry enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { orginSum += [obj integerValue]; }]; int halfSum = (int)orginSum/2; for (int i = 0 ; i< inputArry.count; i++) { for (int j = halfSum; j >= [inputArry[i] intValue]; j--) { if ([dpArry[j] intValue] < [dpArry[j-[inputArry[i] intValue]] intValue] + [inputArry[i] intValue]) { dpArry[j] = [NSString stringWithFormat:@"%d",[dpArry[j-[inputArry[i] intValue]] intValue] + [inputArry[i] intValue]]; TempState *temp = [[TempState alloc] init]; temp.iIdx = i; temp.jIdx = j; [tempStateArry addObject:temp]; } } } NSLog(@"dpArry:%@",dpArry); NSLog(@"tempStateArry:%@",tempStateArry); __block int jdx = halfSum; for (int index = (int)inputArry.count - 1 ; index >= 0; index --) { // [4 12] // [3 12] j = 12 - 6 = 6 inputArry[3] = 6 // [2 6] // [1 6] j = 6 - 4 = 2 inputArry[1] = 4 // [0 2] j = 2 - 2 = 0 inputArry[0] = 2 [tempStateArry enumerateObjectsUsingBlock:^(TempState * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { TempState *temp = tempStateArry[idx]; NSLog(@"index:%d & temp.iIdx:%d & temp.iIdx:%d",index,temp.iIdx,temp.jIdx); if (index == temp.iIdx && jdx == temp.jIdx) { NSLog(@"temp.iIdx:%d & temp.iIdx:%d & inputArry[idx]:%@",temp.iIdx,temp.jIdx,inputArry[index]); [outputArry addObject:inputArry[index]]; jdx -= [inputArry[index] integerValue]; NSLog(@"jdx:%d",jdx); *stop = YES; } }]; } NSLog(@"最后结果outputArry:%@",_outputArry); }
最后结果: 【2,4,6】 【5,7】