[英]dynamic programming - print all subsets with the given sum
I am practicing some dynamic programming problem and was trying to solve the problem to print all subsets with the given sum. 我正在练习一些动态编程问题,并试图解决该问题,以给定的总和打印所有子集。 For eg : For the
set :{1,2,3,4,5}
and sum value = 10
, I should get the below results: 例如:对于
set :{1,2,3,4,5}
, sum value = 10
,我应该得到以下结果:
[1, 2, 3, 4]
[1, 4, 5]
[2, 3, 5]
I am getting the required result without using table
, which I used to prevent repetitive calls for same i
and sum
. 我无需使用
table
得到所需的结果,过去我使用了table
来防止重复调用相同的i
和sum
。 But I am not getting [2, 3, 5]
in the output when using table
. 但是当使用
table
时,我的输出没有得到[2, 3, 5]
。
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});
}
Please help ! 请帮忙 ! !
! !
!
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
}
}
That line marks table[4][5] as true, i=4, list=[2, 3] sum=5 will match table[i][sum] == true 该行将table [4] [5]标记为true,i = 4,list = [2,3] sum = 5将匹配table [i] [sum] == true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.