I am confused how to write this in JAVA: There exists a staircase with N steps, and you can climb up either 1 or 2 steps at a time. Given N, write a function that returns the number of unique ways you can climb the staircase. The order of the steps matters.
For example, if N is 4, then there are 5 unique ways:
1, 1, 1, 1
2, 1, 1
1, 2, 1
1, 1, 2
2, 2
What if, instead of being able to climb 1 or 2 steps at a time, you could climb any number from a set of positive integers X? For example, if X = {1, 3, 5}, you could climb 1, 3, or 5 steps at a time.
Basically, I could do the first part and understand the logics with harder part with the set that the answer is: f(n) = f(n-1) + f(n-3) + f(n-5). Can anyone help me? This is mine approach:
public static void main(String[] args) {
int n = 4;
Set < Integer > list = new HashSet < Integer > ();
list.add(1);
list.add(3);
list.add(5);
int ways = reachNFloorSet(list, n, 0);
// int ways = reachNFloor(n);
System.out.println(n + " Floor is reached in " + ways + " different way/s.");
}
public static int reachNFloor(int n) { // easy part
if (n <= 1) {
return 1;
}
return reachNFloor(n - 1) + reachNFloor(n - 2);
}
public static int reachNFloorSet(Set < Integer > numbers, int n, int sum) {
if (n < 0) {
return 0;
} else if (n == 0) {
return 1;
}
for (Integer x: numbers) {
if (x <= n) {
sum += reachNFloorSet(numbers, n - x, sum);
}
}
return sum;
}
I think that the problem is with the for loop, but I cannot figure how to make it correct.
reachNFloor
works fine without asum
parameter, why did you makereachNFloorSet
take asum
parameter? Get rid of it to fix you problem.