Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3142
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  青春惊慌失措
    2020-11-21 06:56

    I ported the C# sample to Objective-c and didn't see it in the responses:

    //Usage
    NSMutableArray* numberList = [[NSMutableArray alloc] init];
    NSMutableArray* partial = [[NSMutableArray alloc] init];
    int target = 16;
    for( int i = 1; i= target)
        { return; }
    
        for (int i = 0;i < [numbers count];i++ )
        {
            int n = [numbers[i] intValue];
            NSMutableArray* remaining = [[NSMutableArray alloc] init];
            for (int j = i + 1; j < [numbers count];j++)
            { [remaining addObject:@([numbers[j] intValue])]; }
    
            NSMutableArray* partRec = [[NSMutableArray alloc] initWithArray:partial];
            [partRec addObject:@(n)];
            [self findSums:remaining target:target part:partRec];
        }
    }
    

提交回复
热议问题