Problem:


Score : 400 points

Problem Statement

In this problem, we only consider strings consisting of lowercase English letters.

Strings s and t are said to be isomorphic when the following conditions are satisfied:

|s| = |t| holds.

For every pair i, j, one of the following holds:

s_i = s_j and t_i = t_j.

s_i \neq s_j and t_i \neq t_j.

For example, abcac and zyxzx are isomorphic, while abcac and ppppp are not.

A string s is said to be in normal form when the following condition is satisfied:

For every string t that is isomorphic to s, s \leq t holds. Here \leq denotes lexicographic comparison.

For example, abcac is in normal form, but zyxzx is not since it is isomorphic to abcac, which is lexicographically smaller than zyxzx.

You are given an integer N.
Print all strings of length N that are in normal form, in lexicographically ascending order.

Constraints

1 \leq N \leq 10

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N

Output

Assume that there are K strings of length N that are in normal form: w_1, \ldots, w_K in lexicographical order.
Output should be in the following format:

w_1
:
w_K

Sample Input 1

1

Sample Output 1

a

Sample Input 2

2

Sample Output 2

aa
ab



Sample input:
1


Sample output:
a

Submission status: Wrong Answer

Solution code:
def solve(ans, p, n):
    if len(p) == n:
        s = ""
        for v in p:
            s += chr(ord("a")+v)
        ans.append(s)
        return
    for v in range(p[-1]+2):
        p.append(v)
        solve(ans, p, n)
        p.pop()
    return

def main():
    n = int(input())
    ans = []
    p = [0]
    solve(ans, p, n)
    ans.sort()
    for v in ans:
        print(v)

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(1000000)
n=int(input())


def dfs(s,x):
  if len(s)==n:
    print(s)
  else:
    for i in range(x):
      dfs(s+chr(ord("a")+i),i+1)
    dfs(s+chr(ord("a")+x),x+1)  
dfs("a",1)

Submission status: Wrong Answer

Solution code:
n = int(input())
def dfs(d, val, alp):
    if d == n:
        alp.append(val)
        return
    for i in range (ord('a'), ord(val[-1]) + 2):
        nval = val + chr(i)
        dfs(d+1, nval , alp)

alp = []
dfs(1, 'a', alp)
for i in range(len(alp)):
    print(alp[i])

Submission status: Wrong Answer

Solution code:
import sys
n=int(input())

a=ord('a')
w=[]
for i in range(n):
    w.append(chr(a))
if n==1:
    print('a')
    sys.exit()
if n==2:
    for i in range(n):
        w[-1]=chr(a+i)
        print(''.join(w))

def dd(i,j,n):
    if n>j:
        if (i-j)<0:
            w[-j]=chr(a)
        else:
            w[-j]=chr(a+(i-j))
        dd(i,j+1,n)

for i in range(3,n+1):
    if n>3:
        dd(i,3,n)
    for j in range(1,i):
        if n>2:
            w[-2]=chr(a+(j-1))
        for k in range(j+1):
            if n>1:
                w[-1]=chr(a+k)
                print(''.join(w))

Submission status: Wrong Answer

Solution code:
n=int(input())

def dfs(n, s):
    if len(s)==n:
        print(s)
    else:
        dfs(n, s=s+chr(ord(s[-1])))
        dfs(n, s=s+chr(ord(s[-1])+1))

dfs(n, "a")

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def f(s, last, N):
    if len(s) == N:
        print(s)
        return

    for i in range(last+1):
        f(s + l_alp[i], i+1, N)


def main():
    N = I()
    ans = []

    f('a', 1, N)

    for a in ans:
        print(a)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()

# アルファベットと数字の対応
alp_to_num = {chr(i+97): i for i in range(26)}
ALP_to_num = {chr(i+97).upper(): i for i in range(26)}
num_to_alp = {i: chr(i+97) for i in range(26)}
num_to_ALP = {i: chr(i+97).upper() for i in range(26)}


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    N = NI()
    ans = []

    def dfs(s, i):
        if i == N:
            ans.append(s)
            return

        if s[-1] == "a":
            dfs(s + "a", i+1)
            dfs(s + "b", i+1)
        else:
            num = alp_to_num[s[-1]]
            dfs(s + num_to_alp[num-1], i+1)
            dfs(s + num_to_alp[num], i+1)
            dfs(s + num_to_alp[num+1], i+1)

    dfs("a", 1)
    ans.sort()
    for a in ans:
        print(a)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
import sys
import math
from collections import deque

sys.setrecursionlimit(1000000)
MOD = 10 ** 9 + 7
input = lambda: sys.stdin.readline().strip()
NI = lambda: int(input())
NMI = lambda: map(int, input().split())
NLI = lambda: list(NMI())
SI = lambda: input()

# アルファベットと数字の対応
alp_to_num = {chr(i+97): i for i in range(26)}
ALP_to_num = {chr(i+97).upper(): i for i in range(26)}
num_to_alp = {i: chr(i+97) for i in range(26)}
num_to_ALP = {i: chr(i+97).upper() for i in range(26)}


def make_grid(h, w, num): return [[int(num)] * w for _ in range(h)]


def main():
    N = NI()
    ans = []

    def dfs(s, i):
        if i == N:
            ans.append(s)
            return

        if s[-1] == "a":
            dfs(s + "a", i+1)
            dfs(s + "b", i+1)
        else:
            num = alp_to_num[s[-1]]
            dfs(s + num_to_alp[num-1], i+1)
            dfs(s + num_to_alp[num], i+1)
            dfs(s + num_to_alp[num+1], i+1)

    dfs("a", 1)
    for a in ans:
        print(a)



if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
import itertools
from itertools import permutations, combinations, accumulate
import sys
import bisect
import string
import math
import time


def I(): return int(input())


def S(): return input()


def MI(): return map(int, input().split())


def MS(): return map(str, input().split())


def LI(): return [int(i) for i in input().split()]


def LI_(): return [int(i)-1 for i in input().split()]


def StoI(): return [ord(i)-97 for i in input()]


def ItoS(nn): return chr(nn+97)


def input(): return sys.stdin.readline().rstrip()


def show(*inp, end='\n'):
    if show_flg:
        print(*inp, end=end)


YNL = {False: 'No', True: 'Yes'}
YNU = {False: 'NO', True: 'YES'}
MOD = 10**9+7
inf = float('inf')
IINF = 10**19
l_alp = string.ascii_lowercase
u_alp = string.ascii_uppercase
ts = time.time()
sys.setrecursionlimit(10**6)
nums = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']

show_flg = False
# show_flg = True


def f(s, k, N):
    if len(s) == N:
        print(s)
        return

    for i in range(k+1):
        f(s + l_alp[i], i+1, N)


def main():
    N = I()
    ans = []

    f('a', 1, N)

    for a in ans:
        print(a)


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
def getN():
    return int(input())
def getNM():
    return map(int, input().split())
def getList():
    return list(map(int, input().split()))
def getArray(intn):
    return [int(input()) for i in range(intn)]
def input():
    return sys.stdin.readline().rstrip()
def rand_N(ran1, ran2):
    return random.randint(ran1, ran2)
def rand_List(ran1, ran2, rantime):
    return [random.randint(ran1, ran2) for i in range(rantime)]
def rand_ints_nodup(ran1, ran2, rantime):
  ns = []
  while len(ns) < rantime:
    n = random.randint(ran1, ran2)
    if not n in ns:
      ns.append(n)
  return sorted(ns)

def rand_query(ran1, ran2, rantime):
  r_query = []
  while len(r_query) < rantime:
    n_q = rand_ints_nodup(ran1, ran2, 2)
    if not n_q in r_query:
      r_query.append(n_q)
  return sorted(r_query)

from collections import defaultdict, deque, Counter
from sys import exit
from decimal import *
import heapq
import math
from fractions import gcd
import random
import string
import copy
from itertools import combinations, permutations, product
from operator import mul
from functools import reduce
from bisect import bisect_left, bisect_right

import sys
sys.setrecursionlimit(1000000000)
mod = 10 ** 9 + 7

#############
# Main Code #
#############

N = getN()

str_l = 'abcdefghij'

ans = [0]
ans_str = []

def alter(array):
    s = ""
    for i in array:
        s += str_l[i]
    return s
def dfs(array):
    if len(array) == N:
        ans_str.append(alter(array))
        return
    for i in range(array[-1] + 2):
        new_array = copy.deepcopy(array)
        new_array.append(i)
        dfs(new_array)

dfs(ans)
ans_str.sort()

for i in ans_str:
    print(i)

Submission status: Wrong Answer

Solution code:
N = int(input())
alp = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
l = []

def dfs(s, n, l):
    if n == 0:
        l.append(s[::-1])
        return
    else:
        n -= 1
        for i in range(n+1):
            dfs(s+alp[i], n, l)

dfs("", N, l)
l.sort()
print(*l, sep="\n")

Submission status: Wrong Answer

Solution code:
from string import ascii_lowercase
N = int(input())
ans = ['a']
for i in range(1, N):
    ans2 = []
    for a in ans:
        for b in ascii_lowercase[:i + 1]:
            ans2 += [a + b]
    ans = ans2
print('\n'.join(ans))

Submission status: Wrong Answer

Solution code:
import string
N = int(input())
abc = string.ascii_lowercase
ans = ['a']
for i in range(2, N):
    ans2 = []
    for a in ans:
        for b in abc[:i]:
            ans2 += [a + b]
    ans = ans2
print('\n'.join(ans))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int):
    def f(i, pre):
        if i == N:
            yield ""
            return
        for s in f(i+1, ord('a')):
            yield "a" + s
        for s in f(i+1, pre+1):
            yield chr(pre+1) + s
    return ['a' + s for s in f(1, ord('a'))]


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    print(*solve(N), sep="\n")

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3
import sys


def solve(N: int):
    def f(i, pre):
        if i == N:
            yield ""
            return
        for s in f(i+1, ord('a')):
            yield s + "a"
        for s in f(i+1, pre+1):
            yield s + chr(pre+1)
    return ['a' + s for s in f(1, ord('a'))]


# Generated by 1.1.7.1 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    print(*solve(N), sep="\n")

def test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    #test()
    main()

Submission status: Wrong Answer

Solution code:
n = int(input())

alp = [chr(i) for i in range(97, 97+26)]

def dfs(i):
    if i == 1:
        return [("a", 1)]
    else:
        ret = []
        for i in dfs(i-1):
            nowstr, nowmax = i
            for j in range(nowmax+1):
                ret.append((nowstr+alp[j], max(j,nowmax)))
        return ret

ans = dfs(n)
#print(ans)
for i in range(len(ans)):
    print(ans[i][0])

Submission status: Wrong Answer

Solution code:
n = int(input())
res = [-1] * n
def do(a, b):
    #print("do",a,b)
    if a >= n:
        return
    res[a] = b
    if a == n - 1:
        print("".join(list(map(lambda x: chr(ord("a") - 1 + x), res))))
        return
    for i in range(1, b + 2):
        do(a + 1, i)

do(0, 1)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10 ** 8)
n = int(input())
alp = "abcdefghijklmnopqrstuvwxyz"
permutations = []

def dfs(a, size):
    if len(a) == size:
        global permutations
        permutations.append(a)
        return
    for i in range(1, a[-1] + 2):
        dfs(a + [i], size)

dfs([1], n)
for i in permutations:
    print(''.join([alp[j-1] for j in i]))

Submission status: Wrong Answer

Solution code:
#!/usr/bin/env python3

import sys
from typing import Any, Callable, Deque, Dict, List, Mapping, Optional, Sequence, Set, Tuple, TypeVar, Union
# import time
# import math
# import numpy as np
# import scipy.sparse.csgraph as cs            # csgraph_from_dense(ndarray, null_value=inf), bellman_ford(G, return_predecessors=True), dijkstra, floyd_warshall
# import random                                # random, uniform, randint, randrange, shuffle, sample
import string                                # ascii_lowercase, ascii_uppercase, ascii_letters, digits, hexdigits
# import re                                    # re.compile(pattern) => ptn obj; p.search(s), p.match(s), p.finditer(s) => match obj; p.sub(after, s)
# from bisect import bisect_left, bisect_right # bisect_left(a, x, lo=0, hi=len(a)) returns i such that all(val<x for val in a[lo:i]) and all(val>-=x for val in a[i:hi]).
# from collections import deque                # deque class. deque(L): dq.append(x), dq.appendleft(x), dq.pop(), dq.popleft(), dq.rotate()
# from collections import defaultdict          # subclass of dict. defaultdict(facroty)
# from collections import Counter              # subclass of dict. Counter(iter): c.elements(), c.most_common(n), c.subtract(iter)
# from datetime import date, datetime          # date.today(), date(year,month,day) => date obj; datetime.now(), datetime(year,month,day,hour,second,microsecond) => datetime obj; subtraction => timedelta obj
# from datetime.datetime import strptime       # strptime('2019/01/01 10:05:20', '%Y/%m/%d/ %H:%M:%S') returns datetime obj
# from datetime import timedelta               # td.days, td.seconds, td.microseconds, td.total_seconds(). abs function is also available.
# from copy import copy, deepcopy              # use deepcopy to copy multi-dimentional matrix without reference
# from functools import reduce                 # reduce(f, iter[, init])
# from functools import lru_cache              # @lrucache ...arguments of functions should be able to be keys of dict (e.g. list is not allowed)
# from heapq import heapify, heappush, heappop # built-in list. heapify(L) changes list in-place to min-heap in O(n), heappush(heapL, x) and heappop(heapL) in O(lgn).
# from heapq import nlargest, nsmallest        # nlargest(n, iter[, key]) returns k-largest-list in O(n+klgn).
# from itertools import count, cycle, repeat   # count(start[,step]), cycle(iter), repeat(elm[,n])
# from itertools import groupby                # [(k, list(g)) for k, g in groupby('000112')] returns [('0',['0','0','0']), ('1',['1','1']), ('2',['2'])]
# from itertools import starmap                # starmap(pow, [[2,5], [3,2]]) returns [32, 9]
# from itertools import product, permutations  # product(iter, repeat=n), permutations(iter[,r])
# from itertools import combinations, combinations_with_replacement
# from itertools import accumulate             # accumulate(iter[, f])
# from operator import itemgetter              # itemgetter(1), itemgetter('key')
# from fractions import Fraction               # Fraction(a, b) => a / b ∈ Q. note: Fraction(0.1) do not returns Fraciton(1, 10). Fraction('0.1') returns Fraction(1, 10)



def main():
    mod = 1000000007                # 10^9+7
    inf = float('inf')              # sys.float_info.max = 1.79e+308
    # inf = 2 ** 63 - 1             # (for fast JIT compile in PyPy) 9.22e+18
    sys.setrecursionlimit(10**6)    # 1000 -> 1000000
    def input(): return sys.stdin.readline().rstrip()
    def ii():    return int(input())
    def isp():   return input().split()
    def mi():    return map(int, input().split())
    def mi_0():  return map(lambda x: int(x)-1, input().split())
    def lmi():   return list(map(int, input().split()))
    def lmi_0(): return list(map(lambda x: int(x)-1, input().split()))
    def li():    return list(input())
    
    
    n = ii()
    
    def create_string(digit, buf):
        if digit == n:
            print(''.join(buf))
        else:
            for char in string.ascii_lowercase[:digit+1]:
                create_string(digit+1, buf+[char])
    
    create_string(0, [])
    
    

if __name__ == "__main__":
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

def offset(strings,k):
    ret = ''
    for i in range(k):
        ret += chr(ord(strings[i]) + 1)
    ret += strings[k:]
    return ret

def stds(n):
    if n == 1:
        return set(['a'])
    else:
        std = stds(n-1)
        ret = set([])
        for stdi in std:
            for i in range(n):
                ret.add('a' + offset(stdi,i))
#                print(ret)
        return ret

def main():
    N = int(input())
    ret = list(stds(N))
    ret.sort()
    print('\n'.join(ret))

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
#!/usr/bin python3
# -*- coding: utf-8 -*-

def offset(strings):
    ret = ''
    for si in strings:
        ret += chr(ord(si) + 1)
    return ret

def stds(n):
    if n == 1:
        return set(['a'])
    else:
        std = stds(n-1)
        ret = set([])
        for stdi in std:
            ret.add('a' + stdi)
            ret.add('a' + offset(stdi))
        return ret

def main():
    N = int(input())
    ret = list(stds(N))
    ret.sort()
    print('\n'.join(ret))


if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
alpha = "abcdefghijklmnopqrstuvwxyz"
ans = []
n = int(input())
def saiki(s):
    global ans
    if len(s) == n:
        ans.append(s)
    else:
        i = alpha.index(s[-1])
        for j in range(i+2):
            saiki(s+alpha[j])
saiki("a")
print("\n".join(ans))

Submission status: Wrong Answer

Solution code:
alpha = "abcdefghijklmnopqrstuvwxyz"
ans = []
n = int(input())
def saiki(s):
    global ans
    if len(s) == n:
        ans.append(s)
    else:
        i = alpha.index(s[-1])
        for j in range(i+2):
            saiki(s+alpha[j])
saiki("a")
print("\n".join(ans))

Submission status: Wrong Answer

Solution code:
n = int(input())


def dfs(n, s):
    l = len(s)
    if n == l:
        print(s)
        return
    alpha = "abcdefghijklmnopqrstuvwxyz"
    for i in range(l + 1):
        dfs(n, s + alpha[i])


dfs(n, "")

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)
def dfs(s):
    if len(s)==N:
        li.append(s)
        return
    o=ord(s[-1])
    for c in range(97,o+2):
        dfs(s+chr(c))

N=int(input())
li=[]
dfs('a')
print(*li,sep='\n')

Submission status: Wrong Answer

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
# list(map(int, list(input()))) # スペースがない数字リストを読み込み
import math
import fractions
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
import collections
from collections import Counter
from collections import deque
import pprint

sr = lambda: input()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""


def factorization(n):
    arr = []
    temp = n
    if n == 1:
        return arr

    for i in range(2, int(-(-n ** 0.5 // 1)) + 1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr.append([i, cnt])

    if temp != 1:
        arr.append([temp, 1])

    if arr == []:
        arr.append([n, 1])

    return arr


# a^n
def power(a, n, mod):
    x = 1
    while n:
        if n & 1:
            x *= a % mod
        n >>= 1
        a *= a % mod
    return x % mod


# n*(n-1)*...*(l+1)*l
def kaijo(n, l, mod):
    if n == 0:
        return 1
    a = n
    tmp = n - 1
    while (tmp >= l):
        a = a * tmp % mod
        tmp -= 1
    return a


inf = 10 ** 18
mod = 10 ** 9 + 7

n = ir()
ans = []
def solve(i,s):
    if i == n:
        ans.append(s)
    else:
        for k in range(ord(s[-1])-ord('a')+2):
            solve(i+1,''.join([s,chr(ord('a')+k)]))

solve(1,'a')

ans.sort()
for num in ans:
    print(num)

Submission status: Wrong Answer

Solution code:
# input()
# int(input())
# map(int, input().split())
# list(map(int, input().split()))
# list(map(int, list(input()))) # スペースがない数字リストを読み込み
import math
import fractions
import sys
import bisect
import heapq  # 優先度付きキュー(最小値取り出し)
import collections
from collections import Counter
from collections import deque
import pprint

sr = lambda: input()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))

"""nを素因数分解"""
"""2以上の整数n => [[素因数, 指数], ...]の2次元リスト"""


def factorization(n):
    arr = []
    temp = n
    if n == 1:
        return arr

    for i in range(2, int(-(-n ** 0.5 // 1)) + 1):
        if temp % i == 0:
            cnt = 0
            while temp % i == 0:
                cnt += 1
                temp //= i
            arr.append([i, cnt])

    if temp != 1:
        arr.append([temp, 1])

    if arr == []:
        arr.append([n, 1])

    return arr


# a^n
def power(a, n, mod):
    x = 1
    while n:
        if n & 1:
            x *= a % mod
        n >>= 1
        a *= a % mod
    return x % mod


# n*(n-1)*...*(l+1)*l
def kaijo(n, l, mod):
    if n == 0:
        return 1
    a = n
    tmp = n - 1
    while (tmp >= l):
        a = a * tmp % mod
        tmp -= 1
    return a


inf = 10 ** 18
mod = 10 ** 9 + 7

n = ir()
ans = []
def solve(i,s):
    if i == n:
        ans.append(s)
    else:
        for k in range(i+1):
            solve(i+1,''.join([s,chr(ord('a')+k)]))

solve(1,'a')

ans.sort()
for num in ans:
    print(num)

Submission status: Wrong Answer

Solution code:
import sys
import heapq
import re
from itertools import permutations
from bisect import bisect_left, bisect_right
from collections import Counter, deque
from math import factorial, sqrt, ceil, gcd
from functools import lru_cache, reduce
from decimal import Decimal
INF = 1 << 60
MOD = 1000000007
sys.setrecursionlimit(10 ** 7)

# UnionFind
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

# ダイクストラ
def dijkstra_heap(s, edge, n):
    #始点sから各頂点への最短距離
    d = [10**20] * n
    used = [True] * n #True:未確定
    d[s] = 0
    used[s] = False
    edgelist = []
    for a,b in edge[s]:
        heapq.heappush(edgelist,a*(10**6)+b)
    while len(edgelist):
        minedge = heapq.heappop(edgelist)
        #まだ使われてない頂点の中から最小の距離のものを探す
        if not used[minedge%(10**6)]:
            continue
        v = minedge%(10**6)
        d[v] = minedge//(10**6)
        used[v] = False
        for e in edge[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,(e[0]+d[v])*(10**6)+e[1])
    return d

# 素因数分解
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr

# 2数の最小公倍数
def lcm(x, y):
    return (x * y) // gcd(x, y)

# リストの要素の最小公倍数
def lcm_list(numbers):
    return reduce(lcm, numbers, 1)

# リストの要素の最大公約数
def gcd_list(numbers):
    return reduce(gcd, numbers)

# 素数判定
def is_prime(n):
    if n <= 1:
        return False
    p = 2
    while True:
        if p ** 2 > n:
            break
        if n % p == 0:
            return False
        p += 1
    return True


# limit以下の素数を列挙
def eratosthenes(limit):
    A = [i for i in range(2, limit+1)]
    P = []

    while True:
        prime = min(A)
        
        if prime > sqrt(limit):
            break
            
        P.append(prime)
            
        i = 0
        while i < len(A):
            if A[i] % prime == 0:
                A.pop(i)
                continue
            i += 1
            
    for a in A:
        P.append(a)
            
    return P

# 同じものを含む順列
def permutation_with_duplicates(L):

    if L == []:
        return [[]]

    else:
        ret = []

        # set（集合）型で重複を削除、ソート
        S = sorted(set(L))

        for i in S:

            data = L[:]
            data.remove(i)

            for j in permutation_with_duplicates(data):
                ret.append([i] + j)

        return ret


# ここから書き始める
def dfs(cnt, n, ret):
    if cnt == n:
        return ret
    ret2 = []
    for i in ret:
        ret2.append(i + "a")
        ret2.append(i + "b")
    return dfs(cnt + 1, n, ret2)

n = int(input())
ans = sorted(dfs(0, n - 1, ["a"]))
for i in ans:
    print(i)

Submission status: Wrong Answer

Solution code:
import sys
sys.setrecursionlimit(10**7)

readline = sys.stdin.buffer.readline
def readstr():return readline().rstrip().decode()
def readstrs():return list(readline().decode().split())
def readint():return int(readline())
def readints():return list(map(int,readline().split()))
def printrows(x):print('\n'.join(map(str,x)))
def printline(x):print(' '.join(map(str,x)))

n = readint()

ans = [[[0],[0]]]

i = 0
while len(ans[i][0])<n:
    print(ans)
    a = ans[i]
    for x in a[1]:
        ans.append([a[0]+[x],a[1]])
    x = a[1][-1]+1
    ans.append([a[0]+[x],a[1] + [x]])
    i+=1

a_ = ord('a')

for i in range(len(ans)):
    a = ans[i][0]
    if len(a)<n:
        continue
    for x in a[:-1]:
        print(chr(x+a_),end='')
    print(chr(a[-1]+a_))

Submission status: Wrong Answer

Solution code:
N = int(input())

alp = "abcdefghijklmnopqrstuvwxyz"

def dfs(s):
    i = len(s)
    if i == N:
        print(s)
    else:
        index = alp.index(s[-1])
        for i in range(index+2):
            dfs(s+alp[i])

dfs("a")

Submission status: Wrong Answer

Solution code:
N = int(input())

alp = "abcdefghijklmnopqrstuvwxyz"

def dfs(s):
    i = len(s)
    if i == N:
        print(s)
    else:
        if s[-1] == "a":
            dfs(s+"a")
            dfs(s+"b")
        else:
            index = alp.index(s[-1])
            for i in range(index+2):
                dfs(s+alp[i])

dfs("a")

Submission status: Wrong Answer

Solution code:
n = int(input())

def aa(str):
  if len(str) == n:
    print(str)
    return
  for i in range(ord("a"), ord(str[-1])+2):
    aa(str+chr(i))

aa("a")

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = []
start = "a"
stack = []
stack.append(start)
num = ord("a")
while stack:
    v = stack.pop()
    if len(v) == n:
        ans.append(v)
        continue
    nex_num = ord(v[-1])
    for i in range(num, nex_num + 2):
        tuika = chr(i)
        stack.append(v + tuika)
ans.sort()
print(*ans, sep="\n")

Submission status: Wrong Answer

Solution code:
n = int(input())
ans = []
start = "a"
stack = []
stack.append(start)
num = ord("a")
while stack:
    v = stack.pop()
    if len(v) == n:
        ans.append(v)
        continue
    nex_num = ord(v[-1])
    for i in range(num, nex_num + 2):
        tuika = chr(i)
        stack.append(v + tuika)

print(*ans[::-1], sep="\n")

Submission status: Wrong Answer

Solution code:
def dfs(i,sent):
    if len(sent)==N:
        print(sent)
        return
    if i>N:
        return
    for j in range(i+1):
        dfs(max(i,j),sent+chara[j])
    return

N=int(input())
chara=["a","b","c","d","e","f","g","h","i","j"]
chara=chara[:N]
dfs(1,"a")

Submission status: Wrong Answer

Solution code:
# -*- coding: utf-8 -*-
# D

import sys
from collections import defaultdict, deque
from heapq import heappush, heappop
import math
import bisect
from itertools import combinations
input = sys.stdin.readline

# 再起回数上限変更
# sys.setrecursionlimit(1000000)

n = int(input())
if n == 1:
    print('a')
    sys.exit()


def dfs(s, max_char):
    # print(s)
    if len(s) == n:
        print(''.join([chr(s + ord('a')) for s in s]))
    else:
        for c in range(max_char):
            if c < max_char-1:
                dfs(s + [c], max(s)+1)
            else:
                dfs(s + [c], max_char + 1)

dfs([], 1)

Submission status: Wrong Answer

Solution code:
n = int(input())
def dfs(i,s):
    if i == n:
        print(s)
        return
    for j in range(i+1):
        if ord(s[-1]) == 97+j or ord(s[-1]) + 1 == 97+j:
            dfs(i+1,s+chr(97+j))
    return
dfs(1,"a")

Submission status: Wrong Answer

Solution code:
n = int(input())
def dfs(i,s):
    if i == n:
        print(s)
        return
    for j in range(n):
        if ord(s[-1]) <= 97+j:
            dfs(i+1,s+chr(97+j))
    return
dfs(1,"a")

Submission status: Wrong Answer

Solution code:
def dfs(n):
    adj = [chr(i+97) for i in range(26)]
    
    stack = ['a']
    combs = []
    while stack:
        node = stack.pop(0)
        if len(node) == n:
            combs.append(node)
        else:
            limit = ord(node[-1])%97 +2
            for child in adj[:limit]:
                cand = node+child
                stack.append(node+child)
    return combs

def main():
    import sys
    def input(): return sys.stdin.readline().rstrip()
    n = int(input())
    res = dfs(n)
    for ans in res:
        print(ans)


if __name__ == '__main__':
    main()