-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCanPartition.java
More file actions
47 lines (33 loc) · 1001 Bytes
/
Copy pathCanPartition.java
File metadata and controls
47 lines (33 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
Things to remember:
1. use streams to find sum
2. Iterate over a hashset
3. Copy a hashset to another HashSet
*/
class Solution {
public boolean canPartition(int[] nums) {
// sum of all elementes in array
int target = Arrays.stream(nums).sum();
if (target % 2 != 0 || nums.length ==1){
return false;
}
Set<Integer> dp = new HashSet<>();
dp.add(0);
dp.add(nums[0]);
target = target / 2;
for (int i = 1; i < nums.length; i++) {
Iterator<Integer> iter = dp.iterator();
Set<Integer> tempDp = new HashSet<>();
while (iter.hasNext()) {
int val = iter.next();
if (val + nums[i] == target) {
return true;
}
tempDp.add(val + nums[i]);
tempDp.add(val);
}
dp = tempDp;
}
return dp.contains(target) ? true : false;
}
}