Ios 使用递归而不是迭代构建组合
我试图定制在这里给出的解决方案中找到的组合方法:因此它使用递归,而不是使用迭代的解决方案。我尝试自定义此函数的原因是为了提高此函数的性能,因为当阵列开始变大并且有许多组合需要计算时,此函数的速度开始显著减慢Ios 使用递归而不是迭代构建组合,ios,objective-c,recursion,nsarray,Ios,Objective C,Recursion,Nsarray,我试图定制在这里给出的解决方案中找到的组合方法:因此它使用递归,而不是使用迭代的解决方案。我尝试自定义此函数的原因是为了提高此函数的性能,因为当阵列开始变大并且有许多组合需要计算时,此函数的速度开始显著减慢 关于如何做到这一点有什么建议吗?我认为您必须将迭代和递归结合起来。如果你想让它做不同数量的数组,那么我想出了这样的方法 第一次通过迭代法 - (NSArray *)combineArrays:(NSArray *)arrays { // arrays is an array of a
关于如何做到这一点有什么建议吗?我认为您必须将迭代和递归结合起来。如果你想让它做不同数量的数组,那么我想出了这样的方法 第一次通过迭代法
- (NSArray *)combineArrays:(NSArray *)arrays
{
// arrays is an array of arrays of elements that you want to combine.
NSMutableArray *combinations = [NSMutableArray array];
for(NSArray *array in arrays) {
NSMutableArray *temp = [NSMutableArray array];
for (id element in array) {
if (combinations.count == 0) {
// the first level of the array is just all the elements from the first array
[temp addObject:@[element]];
} else {
// copy each array in combinations for each new element and add new element to end
for (NSArray *array in combinations) {
[temp addObject:[array arrayByAddingObject:element];
}
}
}
// save the current combinations
combinations = temp;
}
return combinations;
}
我几乎可以肯定,中间部分可以递归到单个方法中。现在正在努力
- (NSArray *)combineArray:(NSArray *)combinations withArrays:(NSMutableArray *)arrays
{
// if there are no arrays to combine then you are at the end of recursion so return combinations.
if (!array || array.count == 0) {
return combinations;
}
// to start with you "combine" the first array with an empty array
if (!combinations) {
combinations = @[@[]];
}
NSMutableArray *newCombinations = [NSMutableArray array];
NSArray *array = [arrays firstObject];
for (id element in array) {
for (NSArray combination in combinations) {
[newCombinations addObject:[combination arrayByAddingObject:element];
}
}
[arrays removeObjectAtIndex:0];
return [self combineArray:newCombinations withArrays:arrays];
}
像这样的东西可能有用。但它并不比迭代快
看一看这个答案,除了JavaScript之外,它可以满足您的需求。不过,您仍然需要触摸每个数组的每个元素一次。只是为了检查。您想要像链接问题中那样的单个值吗?也就是说,前几个组合只是每个数组中的独立值,没有任何组合。不一定。任何2到任意数量的东西都是我想要的。“最大可能是4个组合。”福格迈斯特,你能告诉我怎么做吗?我在想办法,但不确定它是否比迭代更好。事实上,我只是想到了一些事情。一秒钟…如果实施会更快吗?