Recently I came across a programming question like, given a total and an input k find the total number of ways we can reach total with numbers from 1 to k.
for eg: total = 5, k = 3
the output should be 5
cause we can reach 5 in 5 ways using 1, 2 and 3 as below
1+1+1+1+1
1+1+1+2
1+2+2
1+1 +3
2 + 3
I have come up with the below logic, but it's not completely working as am not doing backtracking (I suppose) which I am not sure on how to do
private static int totalways(int total, int k) {
List<Integer> arr = new ArrayList();
for (int i=0; i<total; i++) {
arr.add(1);
}
int count = 1;
boolean breakLoop = true;
while (breakLoop) {
int last = arr.size()-1;
for (int i=last; i>=1; i--) {
if (arr.get(i) + arr.get(i-1) <= k) {
count++;
int sum = arr.get(i) + arr.get(i-1);
arr.remove(i-1);
arr.remove(i-1);
arr.add(sum);
}
}
if (arr.size() == 2){
breakLoop = false;
}
}
return count;
}
Any help is appreciated.