You receive as an input a number representing sections. Each section is composed of two plots, on either side of the road. You must find all possible ways to construct buildings in the plots, considering that there has to be a space between any two buildings.
Input: int stairs = 4; int climbMax = 2; Output: 5 Explanation: The ways to climb 4 stairs , climbing maximum 2 stairs at a time are: (1, 1, 1, 1), (1, 1, 2), (2, 1, 1), (1, 2, 1), (2, 2). |
Solution:
1. static int countWaysToClimbStairs(int stairs, int climbMax) { 2. int[] countingValues = new int[stairs + 1]; 3. int temporary = 0; 4. countingValues[0] = 1; 5. 6. for (int i = 1; i <= stairs; i++) { 7. int stair = i - climbMax - 1; 8. int previousElement = i - 1; 9. if (stair >= 0) { 10. temporary -= countingValues[stair]; 11. } 12. temporary += countingValues[previousElement]; 13. countingValues[i] = temporary; 14. } 15. return countingValues[stairs]; 16. } 17.
Comentarios