user3633705
user3633705

Reputation: 31

Subset sum with positive and negative integers

I've to implement a variation of the subset sum problem, my input will be positive and negative decimal, also I will need to know the subset, knowing that exists unfortunately it's not enough.

I've tried the algorithms found on wikipedia, but I can't make them work with negative numbers, and also I can't find the way to obtain the subset if it exists.

Could anyone point me where I could find some pseudo-code, documentation or implementation, for this algorithm.

Upvotes: 2

Views: 3614

Answers (1)

Khashayar
Khashayar

Reputation: 2034

I wrote the code in Java it checks all the possibilities

import java.util.*;

public class StackOverFlow {

    public static <T> Set<Set<T>> powerSet(Set<T> originalSet) {
        Set<Set<T>> sets = new HashSet<Set<T>>();
        if (originalSet.isEmpty()) {
            sets.add(new HashSet<T>());
            return sets;
        }
        List<T> list = new ArrayList<T>(originalSet);
        T head = list.get(0);
        Set<T> rest = new HashSet<T>(list.subList(1, list.size())); 
        for (Set<T> set : powerSet(rest)) {
            Set<T> newSet = new HashSet<T>();
            newSet.add(head);
            newSet.addAll(set);
            sets.add(newSet);
            sets.add(set);
        }       
        return sets;
    }

    public static int sumSet(Set<Integer> set){
        int sum =0;
        for (Integer s : set) {
            sum += s;
        }
        return sum;     
    }

    public static void main(String[] args) {
         Set<Integer> mySet = new HashSet<Integer>();
         mySet.add(-1);
         mySet.add(2);
         mySet.add(3);

         int mySum = 4;
         for (Set<Integer> s : powerSet(mySet)) {
             if(mySum == sumSet(s))
                 System.out.println(s + " = " + sumSet(s));
         }
    }
}

I hope it helps

Upvotes: 1

Related Questions