Optimizing subset sum implementation

后端 未结 3 1951
一向
一向 2020-12-11 13:58

I\'m working on a solution to a variant of the subset sum problem, using the below code. The problem entails generating subsets of 11 ints from a larger set (superset) and c

3条回答
  •  臣服心动
    2020-12-11 14:15

    you can try my code ( I tried to only give a psudo code and not to solve your homework completely):

    // array is all the numbers you are looking from them
    // length is the number of arrays
    // pos is the position of the slot you are going to fill
    // max is nomber of slots you have to fill (in your case since you are going for the 11 sets you have to set this value as 11
    // sum is the sum of all the values selected until now
    // searchbegin is the first element you can pick from your array (I'm using this variable to only generate subarrays of the superset (array))
    // target is the targetvalue you are looking for.
    
    void generate_all(int []array, int length, int pos,int max, int sum,int searchbegin,int target)
    {
        if max = pos
            if sum = target
                printselectedresults();
        for i:searchbegin->length-max+pos
            if (sum + array[i] < target)
            {
                addtoresults(i);
                generate_all(array,length,pos+1,max,sum+array[i],i+1,target);
                removefromresults(i);
            }
    }
    

    with all this information I think you can easily Implement this code your target language and use it.

    in my function all the permutations generated are subarrays of superset so no permutation can be generated twice, and also every one is generated at least one time.

提交回复
热议问题