Dynamic Programing approach for a subset sum

前端 未结 4 517
借酒劲吻你
借酒劲吻你 2021-01-15 09:20

Given the following Input

10 4 3 5 5 7

Where

10 = Total Score

4 = 4 players

3 = Score by player 1

5 = Score by player 2
         


        
4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-15 09:41

    Here's the super naive solution that simply generates a power set on your input array and then iterates over each set to see if the sum satisfies the given total. I hacked it together with code already available on StackOverflow.

    O(2n) in time and space. Gross.

    You can use the idea of a Set to store all indices into your arrays, then generate all permutations of those indices, and then use each set of indices to then go back into your array and get the values.

    Input

    • Target: 10
    • Values: [3, 5, 5, 7]

    Code:

    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    class SubsetSum
    {
        public static  Set> powerSet(Set originalSet)
        {
            Set> sets = new HashSet>();
            if (originalSet.isEmpty()) 
            {
                sets.add(new HashSet());
                return sets;
            }
            List list = new ArrayList(originalSet);
            T head = list.get(0);
            Set rest = new HashSet(list.subList(1, list.size())); 
            for (Set set : powerSet(rest))
            {
                Set newSet = new HashSet();
                newSet.add(head);
                newSet.addAll(set);
                sets.add(newSet);
                sets.add(set);
            }       
            return sets;
        }
    
        public static void main(String[] args)
        {
            Set mySet = new HashSet();
            int[] arr={3, 5, 5, 7};
            int target = 10;
            int numVals = 4;
            for(int i=0;i s : powerSet(mySet)) 
            {
                int sum = 0;
                for (Integer e : s)
                {
                    sum += arr[e];
                }
                if (sum == target)
                {
                    String soln = "[ ";
                    for (Integer e : s)
                    {
                        soln += arr[e];
                        soln += " ";
                    }
                    soln += "]";
    
                    System.out.println(soln);
                }
            }
        }
    }
    

    Output

    Solutions:
    [ 5 5 ]
    [ 3 7 ]

    Live Demo

    Once you understand this, perhaps you are ready to begin branch and bound or approximation approaches.

提交回复
热议问题