1 将传进数据数组排序
2 递归求和 (当相加大于特定值 进行内部递归)
1 将数组排序
-(void)textSum:(NSArray *)numArray targetNum:(float)targetNum{
NSMutableArray *array = [NSMutableArray arrayWithArray:numArray];
//先排序/Users/amc/Desktop/choose/choose
for (int i = 0; i < array.count; ++i) {
// 从水底往水面浮,所以从最后一个开始
for (NSInteger j = array.count-1; j > i; j--) {
// 后者比前者还小,将需要交换
if ([array[j] intValue] < [array[j - 1] intValue]) {
[array exchangeObjectAtIndex:j withObjectAtIndex:j-1];
}
}
}
self.array = array;
self.targetNum = targetNum;
for (int i = 0; i < array.count; i++) {
NSMutableArray *addArray = [NSMutableArray array];
[self printNum:i addArray:addArray];
}
}
2 判定数组之和 内递归的实现
-(BOOL)printNum:(NSInteger)index addArray:(NSMutableArray *)addArray{
[addArray addObject:self.array[index]];
float sum = [self sum:addArray];
// NSLog(@"111%@",addArray);
if (sum == self.targetNum) {
// NSLog(@"%@",addArray);
[addArray removeLastObject];
return YES;
}else if (sum >self.targetNum){
[addArray removeLastObject];
return NO;
}else{
for (NSInteger i = index+1; i < self.array.count; i++) {
//递归内循环
if (![self printNum:i addArray:addArray]) {
break;
}
}
[addArray removeLastObject];
return YES;
}
}
3 数组求和
-(CGFloat)sum:(NSArray *)array{
CGFloat sum = 0;
for (NSString *str in array) {
sum += [str floatValue];
}
return sum;
}