Created
December 3, 2015 18:24
-
-
Save junminstorage/3b852ba1323d8a55f4a8 to your computer and use it in GitHub Desktop.
Given a integer array, and a number n. Return true if n can be consisted by a subset of array. For example, arr[]={3, 2, 3, 5}, n=11, return true; arr[]={3, 2, 3, 5}, n=12, return false
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* the algorithm will generate sums for all possible subset of the array | |
* and put them into a hash, return true if the target is found in the hash | |
* the optimization here is to check hash contains the target during the update | |
*/ | |
public static boolean sumOfSubSet(int[] nums, int target){ | |
Set<Integer> sums = new HashSet<Integer>(); | |
//start with empty set | |
sums.add(0); | |
if(sums.contains(target)) | |
return true; | |
for(int num : nums){ | |
//make a copy of the sums we have so far | |
Set<Integer> temp = new HashSet<Integer>(sums); | |
//for each previous sum preSum we add the current number num | |
for(int preSum : sums){ | |
temp.add(preSum + num); | |
} | |
//swap | |
sums = temp; | |
if(sums.contains(target)) | |
return true; | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment