提交 e5a3e4b4 编写于 作者: ishellhub's avatar ishellhub

reformat code

上级 c41d10ab
......@@ -2,15 +2,27 @@ package DynamicProgramming;
public class SubsetSum {
/*
This algorithm will determine if a set of integers contains
a subset that sum to a given integer. The algorithm will
return true if such a subset exists and false otherwise.
This is a dynamic programming implementation.
/**
* Driver Code
*/
public static void main(String[] args) {
int[] arr = new int[]{50, 4, 10, 15, 34};
assert subsetSum(arr, 64); /* 4 + 10 + 15 + 34 = 64 */
assert subsetSum(arr, 99); /* 50 + 15 + 34 = 99 */
assert !subsetSum(arr, 5);
assert !subsetSum(arr, 66);
}
private static boolean subsetSum(int arr[], int n, int sum){
boolean isSum[][] = new boolean[n + 2][sum + 1];
/**
* Test if a set of integers contains a subset that sum to a given integer.
*
* @param arr the array contains integers.
* @param sum target sum of subset.
* @return {@code true} if subset exists, otherwise {@code false}.
*/
private static boolean subsetSum(int[] arr, int sum) {
int n = arr.length;
boolean[][] isSum = new boolean[n + 2][sum + 1];
isSum[n + 1][0] = true;
for (int i = 1; i <= sum; i++) {
......@@ -31,27 +43,4 @@ public class SubsetSum {
return isSum[1][sum];
}
/*
This is a driver method to run the algorithm with four
test values: the first two should evaluate true, and the
last two should evaluate false.
*/
public static void main(String args[]) {
int arr[] = new int[]{50, 4, 10, 15, 34};
int n = arr.length;
// 4 + 10 + 15 + 34 = 64
int sum1 = 64;
// 50 + 15 + 34 = 99
int sum2 = 99;
// No subset of the given array will give a sum
// of 5 or 66
int sum3 = 5;
int sum4 = 66;
System.out.println(subsetSum(arr, n, sum1));
System.out.println(subsetSum(arr, n, sum2));
System.out.println(subsetSum(arr, n, sum3));
System.out.println(subsetSum(arr, n, sum4));
}
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册