import java.util.Vector; import java.lang.System; class SSum{ /* return all subsets of a that add up to t, and null if there is * no such subset */ public static Vector> ssum(int[] a, int t) { return ssumrec(a,0, t); } /* return all subsets of a that add up to t, and null if there is * no such subset */ public static Vector> ssumrec(int[] a, int i, int t) { //basecases if (t==0) { //a solution exists, and its the empty set: so we just //return a new vector with an empty vector as its only //element NOTE: an empty vector is very different than //null, which is returned when no solution exists Vector> v = new Vector>(); v.add(new Vector()); return v; } if (t<0) return null; if (i>= a.length) return null; //if we are here, its not the basecase Vector> with, without; with = ssumrec(a,i+1, t-a[i]); without = ssumrec(a, i+1, t); if (with != null) { //we need to add a[i] to each subset in with //if with is empty, it mans this is the first element in the set for (int k=0; k< with.size(); k++) with.get(k).add(a[i]); } //return with + without if (with == null && without == null) return null; Vector> v = new Vector>(); if (with != null) v.addAll(with); if (without != null) v.addAll(without); return v; } public static Vector> ssum2(int[] a, int t) { return ssumrec2(a,0,new Vector(), t); } /* soFar is the partial set so far, and i is the element we are * currently considering. return all subsets of a that add up to * t, and null if there is no such subset */ public static Vector> ssumrec2(int[] a, int i, Vector soFar, int t) { //basecases if (t==0) { //return a vector that contains soFar as its only element Vector> v = new Vector>(); v.add(soFar); return v; } if (t<0) return null; if (i>= a.length) return null; //if we are here, its not the basecase Vector> with, without; Vector soFar2 = (Vector)soFar.clone(); soFar.add(a[i]); with = ssumrec2(a,i+1, soFar, t-a[i]); without = ssumrec2(a, i+1, soFar2, t); //return with + without if (with == null && without == null) return null; Vector> v = new Vector>(); if (with != null) v.addAll(with); if (without != null) v.addAll(without); return v; } public static void main(String[] args) { if (args.length <2) { System.out.println("Incorrect arguments"); System.exit(1); } //set the target int target = Integer.parseInt(args[0]); System.out.println("target=" + target); //set the array int[] a = new int[args.length-1]; for (int i=0; i