Skip to content

Commit d199644

Browse files
authored
Create #SolutionsOfLinearEqtn.java
1 parent 38823ef commit d199644

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/*
2+
https://www.techiedelight.com/total-possible-solutions-linear-equation-k-variables/
3+
4+
Problem is similar to the problem - number of ways to change coin.
5+
We either include the current coefficient or exlcude it.
6+
7+
Recurrence -
8+
count(coeff, k, rhs) = count(coeff, k, rhs-coeff[k]) + count(coeff, k-1, rhs)
9+
where, count(coeff, k, rhs-coeff[k]) --> including coeff[k]
10+
count(coeff, k-1, rhs) --> excluding coeff[k]
11+
*/
12+
13+
//Recursion
14+
15+
public int count(int coeff[], int index, int rhs){
16+
//Base Case: we have considered valid coeff and their summation equals rhs
17+
if(rhs == 0) return 1;
18+
19+
//Base Case: we have considered invalid coeff and their summation does not equals rhs
20+
else if(rhs<0 || index< 0) return 0;
21+
22+
//Include the current coeff
23+
int includeIndex = count(coeff, index, rhs-coeff[index]);
24+
25+
//Exclude the current coeff
26+
int excludeIndex = count(coeff, index-1, rhs);
27+
28+
return include + exclude;
29+
}
30+
31+
32+
//Memoized Recursion
33+
public int count(int coeff[], int index, int rhs, HashMap<String, Integer> map){
34+
35+
//Base Case: we have considered valid coeff and their summation equals rhs
36+
if(rhs == 0) return 1;
37+
38+
//Base Case: we have considered invalid coeff and their summation does not equals rhs
39+
else if(rhs<0 || index< 0) return 0;
40+
41+
String key = index + "|" + rhs;
42+
43+
if(!map.containsKey(key)){
44+
//Include the current coeff
45+
int includeIndex = count(coeff, index, rhs-coeff[index]);
46+
47+
//Exclude the current coeff
48+
int excludeIndex = count(coeff, index-1, rhs);
49+
50+
map.put(key, include + exclude);
51+
}
52+
53+
return map.get(key);
54+
55+
}
56+
57+
58+
/*
59+
Time Complexity - O(numberOfCoefficients * RHS)
60+
Pseudo Polynomial
61+
*/
62+

0 commit comments

Comments
 (0)