OJ2755神器的口袋

import java.util.Scanner;

//神器的口袋~
public class OJ2755 {
static int[] weigth;
static int[][] results;
static int[] results2;
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {
    int number = scanner.nextInt();
    weigth = new int[number + 1];
    results = new int[number + 1][40 + 1];
    results2 = new int[40 + 1];
    for (int i = 1; i <= number; i++) {
        weigth[i] = scanner.nextInt();
    }
    for (int i = 0; i <= number; i++) {
        results[i][0] = 1;
    }
    results2[0] = 1;
    int result = pocket(number, 40);
    System.out.println(result);
    int result2 = pocket2(number, 40);
    System.out.println(result2);
    int result3 = pocket3(number, 40);
    System.out.println(result3);
}

// 递归
private static int pocket(int number, int capacity) {
    if (capacity == 0)
        return 1;
    if (number == 0)
        return 0;
    return pocket(number - 1, capacity) + pocket(number - 1, capacity - weigth[number]);
}

// 递推
private static int pocket2(int number, int capacity) {
    for (int k = 1; k <= number; k++) {
        for (int c = 1; c <= capacity; c++) {
            results[k][c] = results[k - 1][c];
            if (c >= weigth[k])
                results[k][c] += results[k - 1][c - weigth[k]];
        }

    }
    return results[number][capacity];
}

// 递推+滚动数组
private static int pocket3(int number, int capacity) {
    for (int k = 1; k <= number; k++) {
        for (int c = capacity; c > 0; c--) {
            results2[c] = results2[c];
            if (c >= weigth[k])
                results2[c] += results2[c - weigth[k]];
        }
    }
    return results2[capacity];
}

}

你可能感兴趣的:(数据结构,算法)