I'm trying to solve Stair case recursion problem on HackerRank. The problem is to find all possible ways for a child to climb a stair case with height n given that he can jump 1, 2 or 3 steps at a time.
I'm using java Fork join to enhance performance but unfortunately it still slow. My approach is as follows:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;
public class RecursiveStairCase extends RecursiveTask<Integer> {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer stairHeight;
public RecursiveStairCase(Integer stairHeight) {
this.stairHeight = stairHeight;
}
@Override
protected Integer compute() {
return getStairClimbPossibleWays(stairHeight);
}
static int getStairClimbPossibleWays(int stairHeight) {
if (stairHeight < 0)
return 0;
if (stairHeight == 1 || stairHeight == 0)
return 1;
return getStairClimbPossibleWays(stairHeight - 1)
+ getStairClimbPossibleWays(stairHeight - 2)
+ getStairClimbPossibleWays(stairHeight - 3);
}
private List<RecursiveStairCase> createSubtasks() {
List<RecursiveStairCase> subtasks = new ArrayList<RecursiveStairCase>();
RecursiveStairCase subtask1 = new RecursiveStairCase(stairHeight - 1);
RecursiveStairCase subtask2 = new RecursiveStairCase(stairHeight - 2);
RecursiveStairCase subtask3 = new RecursiveStairCase(stairHeight - 3);
subtask1.fork();
subtask2.fork();
subtask3.fork();
subtasks.add(subtask1);
subtasks.add(subtask2);
subtasks.add(subtask3);
return subtasks;
}
public static void main(String[] args) {
Integer result = 0;
long startTime = System.currentTimeMillis();
int[] numbers = new int[] { 32, 33, 35, 36, 36 };
for(int i=0;i<numbers.length;i++){
result = 0;
final RecursiveStairCase recursiveStairCase = new RecursiveStairCase(36);
List<RecursiveStairCase> recursiveStairCases = recursiveStairCase
.createSubtasks();
for (RecursiveStairCase recursiveStairCaseThread : recursiveStairCases) {
result += recursiveStairCaseThread.join();
}
System.out.println(result);
}
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
System.out.println("Consumed:" + elapsedTime);
}
}
I recorded the following test cases/time consumed pairs (which is refused by HackerRank (timed out)).
Test Case #5 {35,30,33,36,20}-->9.47 sec
Test Case #8 {32,33,35,36,36}-->15.531 sec
I need your advice to make it perform faster.