Generate Parentheses
Real-world version: Ridge Walk PlansThe statement here is our own: the same inputs, outputs and technique.
A trail crew is drafting a loop hike along a ridge. The hike is a sequence of steps written as a string, where "U" gains one metre of height and "D" loses one metre.
A plan is valid when all three hold:
- it uses exactly
climbsup steps and exactlyclimbsdown steps, so it is2 * climbssteps long; - the hike ends back at the trailhead height;
- after every single step the hiker is at or above the trailhead height, because the ridge drops away below that line.
Return every valid plan. The plans may be returned in any order.
Examples
Example 1
- Input
- climbs = 2
- Output
- ["UUDD", "UDUD"]
Either both climbs are taken before either descent, or the hiker rises and drops twice in a row. Starting with a descent is ruled out by the third condition.
Example 2
- Input
- climbs = 4
- Output
- ["UUUUDDDD", "UUUDUDDD", "UUUDDUDD", "UUUDDDUD", "UUDUUDDD", "UUDUDUDD", "UUDUDDUD", "UUDDUUDD", "UUDDUDUD", "UDUUUDDD", "UDUUDUDD", "UDUUDDUD", "UDUDUUDD", "UDUDUDUD"]
There are fourteen plans of eight steps that stay at or above the trailhead height and finish level with it.
Constraints
- 1 <= climbs <= 8
The values you return may be in any order.
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def ridge_walk_plans(climbs: int) -> list[str]:public List<String> ridgeWalkPlans(int climbs)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 6 test cases: 6 passed
- Passed: 2 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- Palindrome PartitioningReal-world version: Bead Strand CutsMedium
- Valid Parenthesis StringReal-world version: Salvage a Smudged Span TraceMedium
- Different Ways to Add ParenthesesReal-world version: Every Value a Sum Can Be Grouped IntoMedium
- Longest Valid ParenthesesReal-world version: Longest Clean Trace WindowHard