Count number of ways to reacha given score in a game
Pattern: Subsequences and knapsack
A move scores 3, 5 or 10 points; count the unordered ways to reach n. It is Coin Change II with coins 3, 5 and 10: moves in the outer loop.
No verified practice link yet. The guide below states the problem in full, so you can still solve it here.
The problem
In a game each move scores 3, 5 or 10 points. Return the number of distinct combinations of moves that total exactly n
(order does not matter). n = 8 gives 1. The catalogue has no practice link for this one.
Think first
- Does the order of moves matter?
- Which counting problem is this?
- Which loop goes outside?
Hints
Brute force, and why it fails
List every combination: small but exponential in general.
The key insight
Adding move types one at a time counts each combination once.
Dry run
n = 8. After 3s: scores 0, 3, 6 have one way each.
Step 1 of 2
The plan
ways = [1, 0, ...]
for m in (3, 5, 10): for s from m up to n: ways[s] += ways[s - m]
Complexity
- Time
O(n)- Space
O(n)
Three passes.
Edge cases
- n = 0: 1.
- n = 1, 2, 4: 0.
- Large n.
I've built my logic, show the code
Java
class Solution {
public long count(int n) {
long[] ways = new long[n + 1]; // ways[s]: unordered ways to score s
ways[0] = 1;
for (int move : new int[]{3, 5, 10}) // moves in the outer loop: order of moves does not matter
for (int s = move; s <= n; s++) ways[s] += ways[s - move];
return ways[n];
}
}C++
class Solution {
public:
long long count(int n) {
vector<long long> ways(n + 1, 0); // ways[s]: unordered ways to score s
ways[0] = 1;
int moves[3] = {3, 5, 10};
for (int move : moves) // moves in the outer loop: order of moves does not matter
for (int s = move; s <= n; s++) ways[s] += ways[s - move];
return ways[n];
}
};Python
class Solution:
def count(self, n: int) -> int:
ways = [1] + [0] * n # ways[s]: unordered ways to score s
for move in (3, 5, 10): # moves in the outer loop: order of moves does not matter
for s in range(move, n + 1):
ways[s] += ways[s - move]
return ways[n]Common mistakes
- Counting orders.
- Starting ways[0] = 0.