先前用C语言很容易实现了一个回溯算法,但转到Java后由于面向对象的原因,一时不知道如何处理变量。今天学习了static和final关键字,正好做一个练习。
static: 定义一个类变量,使当前变量可以此类中的任意方法访问
final: 定义一个常量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| package Foundation;
public class Bag {
static final int N = 3; static final int W = 16; static int []w = {10, 8, 5}; static int []v = {5, 4, 1}; static int curValue; static int curWeight; static int bestValue; static int []x = new int[3]; static int []bestX = new int[3]; public static void main(String[] args) { backtracking(0);
System.out.println("最大利润为: " + bestValue); for (int i = 0; i < N; i++) { System.out.println(bestX[i]); } }
public static void backtracking(int k) { if (k > N-1) { if (bestValue < curValue) { bestValue = curValue; for (int i = 0; i < N; i++) { bestX[i] = x[i]; } } } else { for (int i = 0; i <= 1; i++) { x[k] = i; if (i == 0) { backtracking(k+1); } else { if (curWeight + w[k] < W) { curWeight += w[k]; curValue += v[k]; backtracking(k+1); curWeight -= w[k]; curValue -= v[k]; } } } } } }
|