

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Material Type: Notes; Professor: Fuentes; Class: Data Structures; Subject: Computer Science; University: University of Texas - El Paso; Term: Spring 2009;
Typology: Study notes
1 / 2
This page cannot be seen from the preview
Don't miss anything!


public class subSetSum{ // Solving Subset sum using a stack // Programmed by Fuentes, Feb. 9, 2009 // Subset sum consists of finding a subset of mySet whose elements add up to goal // It is a well-known NP-complete problem public static void main(String[] args) { myStack S = new myStack(); int [] mySet ={2,5,8,9,12,21,33}; int lastItem =mySet.length-1; int goal = 61; int x, newItem; S.push(0); int sumStack = mySet[0]; boolean done = false; System.out.println("The Goal is : "+goal); while (!done) { // Uncomment to debug, show stack contents and sum of stack elements S.printSet(mySet); System.out.println("Sum Stack "+sumStack); if (sumStack == goal){ done = true; System.out.println("The Solution is: "); S.printSet(mySet); } else if ((sumStack>goal)|(S.peek()==lastItem)){ //Backtrack System.out.println("Backtracking "); x = S.pop(); sumStack -= mySet[x]; if (x==lastItem){ // No more elements to add if(S.isEmpty()){ done = true; System.out.println("No Solution"); } else{ x = S.pop(); sumStack -= mySet[x]; } } if (!done){ S.push(x+1); sumStack += mySet[x+1]; } } else if (S.peek()<lastItem){ // Add more elements to stack System.out.println("Adding more elements ");
newItem = S.peek()+1; S.push(newItem); sumStack += mySet[newItem]; } else{ // No more elements to add done = true; System.out.println("No Solution"); } } } } //Stack class to be used with subsetSum // Programmed by Fuentes, Feb. 9 2009 public class myStack{ private int [] items; private int top; public myStack(){ items = new int[20]; top=-1; } public void push(int n){ top++; items[top]=n; } public int pop(){ top--; return items[top+1]; } public int peek(){ return items[top]; } public boolean isEmpty(){ return top==-1; } public void printStack(){ for (int i= 0;i <=top;i++) System.out.print(items[i]+" "); System.out.println(); } public void printSet(int [] S){ System.out.print("{"); for (int i= 0;i <=top;i++) System.out.print(S[items[i]]+" "); System.out.println("}"); } }