从小到大排序
1.用OC外层封装的方法
-(NSArray *)combine:(NSArray * )array count:(NSInteger)count{
int arr[array.count];
for (int i = 0; i < array.count; i++)
{
arr[i] = [array[i] intValue];
}
int num = count;
int result[num];
return combine_increase(arr, 0, result, num, num, sizeof(arr)/sizeof(int));
}
2.用C语言和OC混编实现的方法,直接把结果返回
//arr为原始数组
//start为遍历起始位置
//result保存结果,为一维数组
//count为result数组的索引值,起辅助作用
//NUM为要选取的元素个数
//arr_len为原始数组的长度,为定值
NSArray * combine_increase(int* arr, int start, int* result, int count, const int NUM, const int arr_len)
{
NSMutableArray * resultArr = [NSMutableArray array];
int i = 0;
for (i = start; i < arr_len + 1 - count; i++)
{
result[count - 1] = i;
if (count - 1 == 0)
{
int j;
NSMutableArray * subArr = [[NSMutableArray alloc]init];
for (j = NUM - 1; j >= 0; j--){
[subArr addObject:[NSNumber numberWithInt:arr[result[j]]]];
// printf("%d\t",arr[result[j]]);
}
[resultArr addObject:subArr];
// printf("\n");
}
else
[resultArr addObjectsFromArray:combine_increase(arr, i + 1, result, count - 1, NUM, arr_len)];
}
return resultArr;
}
3.纯C语言实现
//arr为原始数组
//start为遍历起始位置
//result保存结果,为一维数组
//count为result数组的索引值,起辅助作用
//NUM为要选取的元素个数
//arr_len为原始数组的长度,为定值
void combine_increase(int* arr, int start, int* result, int count, const int NUM, const int arr_len)
{
int i = 0;
for (i = start; i < arr_len + 1 - count; i++)
{
result[count - 1] = i;
if (count - 1 == 0)
{
int j;
for (j = NUM - 1; j >= 0; j--)
printf("%d\t",arr[result[j]]);
printf("\n");
}
else
combine_increase(arr, i + 1, result, count - 1, NUM, arr_len);
}
}
从大到小排序
1.用OC外层封装的方法
-(NSArray *)combine2:(NSArray * )array count:(int)count{
int arr[array.count];
int i;
for (i = 0; i < array.count; i++)
{
arr[i] = [array[i] intValue];
}
int result[count];
return combine_decrease(arr,i, result, count, count);
}
2.用C语言和OC混编实现的方法,直接把结果返回
//arr为原始数组
//start为遍历起始位置
//result保存结果,为一维数组
//count为result数组的索引值,起辅助作用
//NUM为要选取的元素个数
NSArray * combine_decrease(int* arr, int start, int* result, int count, const int NUM)
{
NSMutableArray * resultArr = [NSMutableArray array];
int i;
for (i = start; i >=count; i--)
{
result[count - 1] = i - 1;
if (count > 1)
{
[resultArr addObjectsFromArray:combine_decrease(arr, i - 1, result, count - 1, NUM)];
}
else
{
int j;
NSMutableArray * subArr = [[NSMutableArray alloc]init];
for (j = NUM - 1; j >=0; j--){
[subArr addObject:[NSNumber numberWithInt:arr[result[j]]]];
// printf("%d\t",arr[result[j]]);
}
[resultArr addObject:subArr];
// printf("\n");
}
}
return resultArr;
}
3.纯C语言实现
//arr为原始数组
//start为遍历起始位置
//result保存结果,为一维数组
//count为result数组的索引值,起辅助作用
//NUM为要选取的元素个数
void combine_decrease(int* arr, int start, int* result, int count, const int NUM)
{
int i;
for (i = start; i >=count; i--)
{
result[count - 1] = i - 1;
if (count > 1)
{
combine_decrease(arr, i - 1, result, count - 1, NUM);
}
else
{
int j;
for (j = NUM - 1; j >=0; j--)
printf("%d\t",arr[result[j]]);
printf("\n");
}
}
}