-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPartion_Array.java
More file actions
executable file
·43 lines (30 loc) · 874 Bytes
/
Copy pathPartion_Array.java
File metadata and controls
executable file
·43 lines (30 loc) · 874 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
import java.util.*;
public class Partion_Array {
public static void main(String[] args) {
int a[] = {2,1,2,3, 4, 8};
int sum = 0;
for(int i = 0; i<a.length; i++) {
sum += a[i];
}
ArrayList<Integer> ans = new ArrayList<>();
boolean isPossible = (sum&1) == 0 &&
partition(a, sum/2, 0, ans);
if(isPossible) {
for(int e: ans) {
System.out.print(e+" ");
}
} else {
System.out.println("not possible");
}
}
static boolean partition(int a[], int sum, int i, ArrayList<Integer> ans) {
if(i >= a.length || sum < 0) return false;
if(sum == 0) return true;
ans.add(a[i]);
boolean leftPossible = partition(a, sum-a[i], i+1, ans);
if(leftPossible) return true;
//this makes backtracking possible
ans.remove(ans.size()-1);
return partition(a, sum, i+1, ans);
}
}