package f_recursion.H_demo.demo2;
/**
* 背包问题
*
* @author Administrator
*
*/
public class Demo1 {
static int arr[] = { 11, 8, 7, 6, 5 };
static Stack theStack = new Stack(arr.length);
public static void main(String[] args) {
Operation(20, 0);
}
private static void Operation(int weight, int index) {
System.out.println(index);
if (weight == 0) {
theStack.display();
}
if (index < arr.length && arr[index] < weight) {
theStack.push(index);
weight -= arr[index];
Operation(weight, ++index);
} else if (arr[index] > weight) {
Operation(weight, ++index);
} else if (index == arr.length) {
index = theStack.top();
if (index == 5) {
System.out.println("无法匹配");
} else {
Operation(weight, ++index);
}
}
}
}package f_recursion.H_demo.demo2;
public class Stack {
@SuppressWarnings("unused")
private int max;
private int top;
private int[] arr;
public Stack(int max) {
this.max = max;
arr = new int[max];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int p) {
arr[++top] = p;
}
public int pop() {
return arr[top--];
}
public int peek() {
return arr[top];
}
public int top() {
top=-1;
return arr[0];
}
public void display() {
while (!isEmpty()) {
System.out.print(pop()+" ");
}
}
}
/**
* 背包问题
*
* @author Administrator
*
*/
public class Demo1 {
static int arr[] = { 11, 8, 7, 6, 5 };
static Stack theStack = new Stack(arr.length);
public static void main(String[] args) {
Operation(20, 0);
}
private static void Operation(int weight, int index) {
System.out.println(index);
if (weight == 0) {
theStack.display();
}
if (index < arr.length && arr[index] < weight) {
theStack.push(index);
weight -= arr[index];
Operation(weight, ++index);
} else if (arr[index] > weight) {
Operation(weight, ++index);
} else if (index == arr.length) {
index = theStack.top();
if (index == 5) {
System.out.println("无法匹配");
} else {
Operation(weight, ++index);
}
}
}
}package f_recursion.H_demo.demo2;
public class Stack {
@SuppressWarnings("unused")
private int max;
private int top;
private int[] arr;
public Stack(int max) {
this.max = max;
arr = new int[max];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public void push(int p) {
arr[++top] = p;
}
public int pop() {
return arr[top--];
}
public int peek() {
return arr[top];
}
public int top() {
top=-1;
return arr[0];
}
public void display() {
while (!isEmpty()) {
System.out.print(pop()+" ");
}
}
}