Count the possible ways to construct buildings in JAVA
- oanaunciuleanu

- 22 nov. 2022
- 1 min de citit
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.
Solution:
1. static int countWaysToConstructBuildings(int sections) { 2. if (sections == 1) { 3. return 4; 4. } 5. 6. int countBuildingAtEnd = 1; 7. int countSpaceAtEnd = 1; 8. int previousCountBuilding; 9. int previousCountSpace; 10. 11. for (int i = 2; i <= sections; i++) { 12. previousCountBuilding = countBuildingAtEnd; 13. previousCountSpace = countSpaceAtEnd; 14. 15. countSpaceAtEnd = previousCountBuilding + previousCountSpace; 16. countBuildingAtEnd = previousCountSpace; 17. } 18. 19. int result = countSpaceAtEnd + countBuildingAtEnd; 20. 21. return (result * result); 22. } 23.

Comentarii