-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFindSubArraySum.java
More file actions
78 lines (56 loc) · 1.65 KB
/
FindSubArraySum.java
File metadata and controls
78 lines (56 loc) · 1.65 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.HashSet;
/**
* Find all subsets within an array that adds up to a value K
* @author Kavita Ganesan
*
*/
public class FindSubArraySum {
public static void main (String args[]){
FindSubArraySum fsa=new FindSubArraySum();
fsa.start();
}
/** temporary storage */
HashSet<String> hs=new HashSet<String>();
/** this is the K */
int sumNeeded=4;
/** this is the array */
int [] intArray={4,1,2,1,4,3,2,3};
public void start(){
for(int i=0; i<intArray.length; i++){
hs.clear();
int currSum=0;
int idxCurr=i;
String strCurrSubArray="";
boolean found=findSubArray(currSum,idxCurr,strCurrSubArray);
if(found)
hs.add(Integer.toString(intArray[i]));
if(!hs.isEmpty())
System.out.println(hs);
}
}
private boolean findSubArray(int sumSoFar, int idxCurr, String currSubArrayVals) {
//find the current sum
int currSum=sumSoFar+intArray[idxCurr];
//if its just initialized then assign the str value of the intArray[idxCurr]
if(sumSoFar==0){
currSubArrayVals=intArray[idxCurr]+"";
}
//if found a sum, then return true
if(currSum==sumNeeded)
return true;
//exceeded value, return
if(currSum > sumNeeded)
return false;
//if sum < sumNeeded, then keep searching in the remaining
//elements of the array
for(int i=idxCurr+1; i<intArray.length; i++){
int nextIdx=i;
String subArrayVals=currSubArrayVals+" "+intArray[nextIdx];
boolean found=findSubArray(currSum, nextIdx, subArrayVals);
//if found, add to hashset but continue searching as there may be multiple options
if(found)
hs.add(subArrayVals);
}
return false;
}
}