Олимпиадный тренинг

Задача 31844. Ternary sequences


Задача

Темы: Рекурсия
The number N is entered. Generate in anti-lexicographic order all sequences of length N (1≤N≤9) consisting of the numbers 3, 4, 5, in which the number of triples does not exceed two.
 
In "anti-lexicographic" means "in reverse order of lexigographic" (see example).
 
In "lexicographical order" means that if two sequences coincide at the first X places, but differ at the X+1 place, then the one in which the number at the X+1 place is less should go first.
In the anti-lexicographic, respectively, vice versa. 
 

Examples
# Input Output
1 3
5 5 5
5 5 4
5 5 3
5 4 5
5 4 4
5 4 3
5 3 5
5 3 4
5 3 3
4 5 5
4 5 4
4 5 3
4 4 5
4 4 4
4 4 3
4 3 5
4 3 4
4 3 3
3 5 5
3 5 4
3 5 3
3 4 5
3 4 4
3 4 3
3 3 5
3 3 4
 

Запрещенные операторы:for;while;until