动态编程-打印给定总和的所有子集

时间:2018-12-05 06:25:52

标签: java dynamic-programming

我正在练习一些动态编程问题,并试图解决该问题以打印给定总和的所有子集。例如:对于set :{1,2,3,4,5}sum value = 10,我应该得到以下结果:

[1, 2, 3, 4]
[1, 4, 5]
[2, 3, 5]

我无需使用table就可以得到所需的结果,这是用来防止重复调用相同的isum的。但是在使用[2, 3, 5]时,我的输出没有得到table

    private static void printSubsetsWithSum(int i, int arr[], int sum, List<Integer> list, int j, boolean[][] table, Map<String,Integer> map) {
        if(sum == 0) {
            System.out.println(list);
        } else if(sum < 0 || i >= arr.length) {
            return;
        } else if(table[i][sum]) {
            return ;
        } else if(arr[i] > sum) {
            printSubsetsWithSum(i+1, arr, sum, list, j, table, map);
            table[i][sum] = true;
            map.put( sum + "_" + i + "_" + arr[i], map.getOrDefault(sum + "_" + i + "_" + arr[i], 0) + 1);
        } else {
            list.add(arr[i]);
            printSubsetsWithSum(i+1, arr, sum-arr[i], list, j+1, table, map);
            list.remove(j);
            printSubsetsWithSum(i+1, arr, sum, list, j, table, map);
            map.put( sum + "_" + i + "_" + arr[i], map.getOrDefault(sum + "_" + i + "_" + arr[i], 0) + 1);
            table[i][sum] = true;
        }
    }

    public static void printSubsetsWithSum(int sum, int[] arr) {
        boolean table[][] = new boolean[arr.length][sum+1];
        Map<String,Integer> map = new LinkedHashMap<String,Integer>();
        printSubsetsWithSum(0, arr, sum, new ArrayList<>(), 0, table, map);
        System.out.println(map);
    }

    public static void main(String[] args) {
        printSubsetsWithSum(10, new int[] {1,2,3,4,5});
    }

请帮助! ! !

1 个答案:

答案 0 :(得分:0)

private static void printSubsetsWithSum(int i, int arr[], int sum, List<Integer> list, int j, boolean[][] table, Map<String,Integer> map) {
    if(sum == 0) {
        System.out.println(list);
    } else if(sum < 0 || i >= arr.length) {
        return;
    } else if(table[i][sum]) {
        return ;
    } else if(arr[i] > sum) {
        printSubsetsWithSum(i+1, arr, sum, list, j, table, map);
        table[i][sum] = true;
        map.put( sum + "_" + i + "_" + arr[i], map.getOrDefault(sum + "_" + i + "_" + arr[i], 0) + 1);
    } else {
        list.add(arr[i]);
        printSubsetsWithSum(i+1, arr, sum-arr[i], list, j+1, table, map);
        list.remove(j);
        printSubsetsWithSum(i+1, arr, sum, list, j, table, map);
        map.put( sum + "_" + i + "_" + arr[i], map.getOrDefault(sum + "_" + i + "_" + arr[i], 0) + 1);
        table[i][sum] = true;// <<---- remove this line it works
    }
}

该行将table [4] [5]标记为true,i = 4,list = [2,3] sum = 5将匹配table [i] [sum] == true