iOS开发 ☞ 组合算法

本文介绍了一种使用 Objective-C 实现的组合算法,该算法能够从给定数组中选择特定数量的元素进行组合,并返回所有可能的组合结果。文章通过具体代码展示了如何通过遍历和状态改变的方式生成这些组合。

转自:http://www.cocoachina.com/bbs/read.php?tid=113856

- (NSMutableArray *)zuHeSuanFa:(NSMutableArray *)array chooseCount:(int)m
{     
    int n = [array count];

    if (m > n)
    {
        return nil;
    }

    NSLog(@"从1到%d中取%d个数的组合。。。",n,m);

    NSMutableArray *allChooseArray = [[NSMutableArray alloc] init];
    NSMutableArray *retArray = [array copy];

    // (1,1,1,0,0)
    for(int i=0;i < n;i++)
    {
        if (i < m)
        {
            [array replaceObjectAtIndex:i withObject:@"1"];
        }
        else 
        {
            [array replaceObjectAtIndex:i withObject:@"0"];
        }
    }

    NSMutableArray *firstArray = [[NSMutableArray alloc] init];

    for(int i=0; i<n; i++)
    {
        if ([[array objectAtIndex:i] intValue] == 1) 
        {
//            [firstArray addObject:[NSString stringWithFormat:@"%d",i+1]];
            [firstArray addObject:[retArray objectAtIndex:i]];
        }
    }

    [allChooseArray addObject:firstArray];
//    [firstArray release];

    int count = 0;
    for(int i = 0; i < n-1; i++)
    {
        if ([[array objectAtIndex:i] intValue] == 1 && [[array objectAtIndex:(i + 1)] intValue] == 0)
        {
            [array replaceObjectAtIndex:i withObject:@"0"];
            [array replaceObjectAtIndex:(i + 1) withObject:@"1"];

            for (int k = 0; k < i; k++)
            {
                if ([[array objectAtIndex:k] intValue] == 1)
                {
                    count ++;
                }
            }
            if (count > 0)
            {
                for (int k = 0; k < i; k++)
                {
                    if (k < count)
                    {
                        [array replaceObjectAtIndex:k withObject:@"1"];
                    }
                    else 
                    {
                        [array replaceObjectAtIndex:k withObject:@"0"];
                    }
                }
            }

            NSMutableArray *middleArray = [[NSMutableArray alloc] init];

            for (int k = 0; k < n; k++)
            {
                if ([[array objectAtIndex:k] intValue] == 1)
                {
//                    [middleArray addObject:[NSString stringWithFormat:@"%d",k + 1]];
                    [middleArray addObject:[retArray objectAtIndex:k]];
                }
            }

            [allChooseArray addObject:middleArray];
//            [middleArray release];

            i = -1;
            count = 0;
        }
    }

    return allChooseArray;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值