For a game that has the possibility for the players to score 3, 5 or 10 points, find in how many ways we can reach a certain total score.
Input: int totalScore = 20; Output: 4 Explanation: The possible combinations to reach 20 are: (10, 10), (5, 5, 10), (5, 5, 5, 5) and (3, 3, 3, 3, 3, 5). |
Solution:
1. static int countScore(int totalScore) { 2. 3. int[] scoreCounts = new int[totalScore + 1]; 4. scoreCounts[0] = 1; 5. 6. for (int i = 3; i <= totalScore; i++) { 7. scoreCounts[i] += scoreCounts[i - 3]; 8. } 9. for (int i = 5; i <= totalScore; i++) { 10. scoreCounts[i] += scoreCounts[i - 5]; 11. } 12. for (int i = 10; i <= totalScore; i++) { 13. scoreCounts[i] += scoreCounts[i - 10]; 14. } 15. 16. return scoreCounts[totalScore]; 17. } 18.
Comments