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: Accepted

Solution code:
N = int(input())

w = ["a"]
l = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]

for i in range(N - 1):
  w_init = w
  w = []
  for j in range(len(w_init)):
    for k in range(i + 2):
      if max(w_init[j]) == l[k]:
        for m in range(k + 2):
          w.append(w_init[j] + l[m])

for i in range(len(w)):
  print(w[i])

Submission status: Accepted

Solution code:
d = ['a','b','c','d','e','f','g','h','i','j']

n = int(input())

result = []

def fig(s, mx):
    if len(s) == n:
        result.append(s)
        return
    
    for i in range(mx+1):
        if i == mx:
            mx += 1
        fig(s + d[i], mx)

fig('', 0)
result.sort()

for r in result:
    print(''.join(r))

Submission status: Accepted

Solution code:
from itertools import groupby

n = int(input())
r = 'a',
for _ in range(n - 1):
  r = [s + c for s in r for c, _ in groupby(sorted(s) + [chr(ord(max(s)) + 1)])]
print(*r, sep='\n')

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, radians
from itertools import accumulate, permutations, combinations, product
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left
from fractions import gcd
from heapq import heappush, heappop
from functools import reduce
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(): return list(map(int, input().split()))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7

N = INT()
x = list(product([0, 1], repeat=N))
ans = []

def dfs(s, mx):
	if len(s) == N:
		ans.append(s)
		return
	for i in range(mx+1):
		if i == mx:
			dfs(s+ascii_lowercase[i], mx+1)
		else:
			dfs(s+ascii_lowercase[i], mx)

dfs("", 0)
print(*ans, sep="\n")

Submission status: Accepted

Solution code:
N = int(input())
s = 'a'
def dfs(s,mx):
    if len(s) == N:
        print(s)
        return
    for diff in range(ord(mx)-ord('a')+2):
        nc = chr(ord('a')+diff)
        # print(diff)
        # print(nc)
        nmx = max(nc,mx)
        dfs(s+nc,nmx)
dfs('a','a')

Submission status: Accepted

Solution code:
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabet_i = {v:i for i,v in enumerate("abcdefghijklmnopqrstuvwxyz")}
N = int(input())
ans = []

memo = {}

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

    maxi = max([alphabet_i[c] for c in tmp])
    for c in alphabet[:maxi+2]:
        dfs(tmp+c, i+1)

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

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**9)
def main():
    N = int(input())
    s = ''
    l = []
    def calc3(s, N, i):
        if len(s) == N:
            l.append(s)
            return
        if len(s) > 0:
            s2 = s[:]
            z = i + 2
            for j in range(z):
                st = s[:]
                st += chr(ord('a')+j)
                if j == i + 1:
                    calc3(st[:], N, i+1)
                else:
                    calc3(st[:], N, i)
        else:
            s += 'a'
            calc3(s[:], N, i)
    calc3(s[:], N, 0)
    l = sorted(set(l))
    for i in l:
        print(i)
main()

Submission status: Accepted

Solution code:
# import numpy as np
# import math
# import copy
# from collections import deque
import sys
input = sys.stdin.readline
# sys.setrecursionlimit(10000)


def dfs(s,mx,N):
    if len(s) == N:
        print(s)
    else:
        alpha = 'abcdefghijk'
        for c in range(mx+1):
            if c == mx:
                mx += 1
            dfs(s+alpha[c],mx,N)


def main():
    N = int(input())

    dfs('',0,N)



main()

Submission status: Accepted

Solution code:
import itertools
import sys

n = int(input())
S = [0]*n
while True:
    print("".join(map(lambda x:chr(ord('a')+x),S)))
    for i in range(n-1,0,-1):
        if(i>0 and max(S[:i])>=S[i]):
            S[i] += 1
            for j in range(i+1,n):
                S[j] = 0
            break
    else:
        break

Submission status: Accepted

Solution code:
N = int(input())
import copy

def nex(lis):
    li = copy.copy(lis)
    if len(li) == N:
        print(''.join([chr(97+i) for i in li]))
        return 

    for x in range(max(li)+2):
        li2 = copy.copy(li)
        li2.append(x)
        nex(li2)
        
nex([0])

Submission status: Accepted

Solution code:
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10000000)
INF = 1<<32


def solve(N: int):
    s = 'abcdefghijkl'
    ans = []
    from heapq import heapify, heappop, heappush

    def f(t: str):
        if len(t) == N:
            # heappush(ans, t)
            ans.append(t)
            return
        
        if len(t) >= 2:
            x = s.index(max(list(t)))+2
        else:
            x = len(t)+1
        for i in range(x):
            f(t+s[i])


    
    f('')
    # print(ans)
    c = 0
    # print(len(ans))
    # while len(ans):
    #     print(heappop(ans))
    #     c += 1
    ans.sort()
    for i in ans:
        print(i)


    return



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
    solve(N)

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
#解説AC

n = int(input())

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

            dfs(s + chr(i), chr(ord(mx) + 1) if i == ord(mx) else mx)
dfs('', 'a')

Submission status: Accepted

Solution code:
n = int(input())

def dfs(s, mx):
    if len(s) == n:
        print(s)
    else:
        for c in range(ord('a'), mx+1):
            if c == mx:
                dfs(s + chr(c), mx + 1)
            else:
                dfs(s + chr(c), mx)

dfs('', ord('a'))

Submission status: Accepted

Solution code:
n = int(input())
ans = ['a']
for j in ans:
  if len(j) < n:
    t = list(j)
    t.sort()
    c = ord(t[-1])
    #print(c)
    for i in range(97,c+2):
      l = str(j + chr(i))
      ans.append(l)
chk = []
for i in ans:
  if len(i) == n:
    chk.append(i)
for i in chk:
  print(i)

Submission status: Accepted

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

def create_li(li):
  if len(li) >= n:
    lis.append(li)
    return
  p = max(li)
  for i in range(1, p + 2):
    cp = li[:]
    cp.append(i)
 #   print(cp)
    create_li(cp)

lis = []
  
n = int(input())
pre = [1]
create_li(pre)
lis.sort()
al = ["a","b","c","d","e","f","g","h","i","j"]
ans = set(["".join([al[id-1] for id in i]) for i in lis])
ans = list(ans)
ans.sort()
for i in ans:
  print(i)

Submission status: Accepted

Solution code:
l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

#print([chr(i) for i in range(97, 97+26)])

def adder(n, s, index):
    if (n == 0):
        print(s)
    else:
        #if(n == 1):
        for i in range(index +2):
            adder(n-1, s+l[i],max(i,index))


n = int(input())
#base =
if (n == 1):
    print("a")
elif (n == 2):
    print("aa")
    print("ab")
else:
    adder(n-1,"a",0)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip() 

def resolve():
    N = int(input())
    
    def rec(n, maxchr, ans):
        if n==N:
            print(ans)
        else:
            for i in range(maxchr):
                rec(n+1, maxchr, ans+chr(i+97))
            rec(n+1, maxchr+1, ans+chr(maxchr+97))

    rec(0, 0, '')

if __name__ == '__main__':
    resolve()

Submission status: Accepted

Solution code:
def dfs(s, mx, n):
    if len(s) == n:
        print(s)
        return

    c = 'a'
    while c <= mx:
        nmx = mx
        if c == mx:
            nmx = chr(ord(c) + 1)
        dfs(s + c, nmx, n)
        c = chr(ord(c) + 1)

n = int(input())
dfs("", 'a', n)

Submission status: Accepted

Solution code:
import sys
sr = lambda: sys.stdin.readline().rstrip()
ir = lambda: int(sr())
lr = lambda: list(map(int, sr().split()))
def resolve():
    N = ir()
    def dfs(c, x):
        if len(c) == N:
            print(c)
        else:
            nx = ord(x)-ord('a')
            for i in range(nx+1):
                if i == nx:
                    dfs(c+chr(ord('a')+i), chr(ord(x)+1))
                else:
                    dfs(c+chr(ord('a')+i), x)
    dfs('', 'a')
resolve()

Submission status: Accepted

Solution code:
n=int(input())-1
a='a'
for _ in range(n):
    a=set([s+ c for s in a for c in s+chr(ord(max(s))+1)])
print(*sorted(a),sep='\n')

Submission status: Accepted

Solution code:
N = int(input())
 
#from collections import deque
 
#Q = deque()
 
S = "a"
 
def printer(S,max_s):
    if len(S)==N:
        print(S)
    else:
        max_s = max(ord(S[-1])-ord('a'),max_s)
        for i in range(ord('a'),ord('a')+max_s+2):        
            printer(S + chr(i),max_s)
        
printer(S,0)

Submission status: Accepted

Solution code:
from collections import Counter

N = int(input())
alpha = [chr(i) for i in range(97, 97+26)]
temp = ['a']
result = ['a']
if N >= 2:
  for n in range(2,N+1):
    result = []
    for i in temp:
      temp_list = list(i)
      type = len(Counter(temp_list))
      for j in range(type+1):
        a = i + alpha[j]
        result.append(a)
    temp = result.copy()
print('\n'.join(result))

Submission status: Accepted

Solution code:
n = int(input())

abc = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n"]
# results = []
# if n == 1:
#     results = ["a"]
# elif n == 2:
#     results = ["aa", "ab"]
# elif n == 3:
#     results = ["aaa", "aab", "aba", "abb", "abc"]
# elif n == 4:
#     results = ["aaaa", "aaab", "aaba", "aabb", "aabc", "abaa", "abab", "abac", "abba", "abbb", "abbc", "abca", "abcb", "abcc", "abcd"]

results = []
for i in range(n):
    if i == 0:
        results.append(["a"])
    else:
        standards = []
        for result in results[i-1]:
            abcs = list(set(result))
            abcs.append(abc[len(abcs)])
            for a in abcs:
                standards.append(result + a)
        results.append(standards)

# for result in results:
for result in sorted(results[n-1]):
    print(result)

Submission status: Accepted

Solution code:
n = int(input())
r = 'a',
for _ in range(n - 1):
  r = [s + c for s in r for i, c in enumerate(s + chr(ord(max(s)) + 1)) if c not in s[:i]]
print(*r, sep='\n')

Submission status: Accepted

Solution code:
from collections import deque


def main():
    N = int(input())

    av = ord('a')

    def to_s(ary):
        ans = "".join(map(lambda v: chr(v + av), ary))
        return ans

    def search(i, v, ary):
        if i == N:
            print(to_s(ary))
            return

        for u in range(0, v + 2):
            ary[i] = u
            search(i + 1, max(u, v), ary)

    ary = [0] * N
    search(0, -1, ary)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
# coding: utf-8
# Your code here!
def solv1():
    n=int(input())
    
    a=[[]for i in range(n)]
    a[0]=[[0]]
    
    for i in range(n-1):
        b=[]
        for pa in a[i]:
    #        print(pa)
            el=[j for j in set(pa)]
    #        print(el)
            el.append(max(pa)+1)
            for l in el:
                b+=[pa+[l]]
    #    print(i,b)
        a[i+1]=b
    ans=[j for j in a[n-1]]
        #print(i)
    ans=sorted(ans)
    for i in ans:
        print(''.join([chr(j+97) for j in i]))

solv1()

Submission status: Accepted

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**10
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 main():
    N = I()
    ans = []

    def f(t, k, n):
        if n == N:
            ans.append(t)
            return

        for i in range(k+1):
            f(t+l_alp[i], max(k, i+1), n+1)

    f('a', 1, 1)

    for a in ans:
        print(a)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
rline = sys.stdin.readline

N = int(input())


def dfs(ans, max_c):
    if len(ans) == N:
        print(ans)
    else:
        for i in range(max_c + 1):
            dfs(ans + chr(ord('a') + i), max_c + 1 if i == max_c else max_c)


def solve():
    dfs('', 0)


if __name__ == '__main__':
    solve()

Submission status: Accepted

Solution code:
def dfs(s, upper):
    if len(s) == N:
        print(s)
    else:
        cur = 'a'
        while cur <= upper:
            dfs(s + cur, chr(ord(cur) + 1) if cur == upper else upper)
            cur = chr(ord(cur) + 1)


N = int(input())
dfs('', 'a')

Submission status: Accepted

Solution code:
N = int(input())
al = "abcdefghijklmnopqrstuvwxyz"
atoi = {s:i for i, s in enumerate(al)}

def func(s, i):
    if i == N:
        print(s)
        return

    maxi = max([atoi[c] for c in s])
    for c in al[:maxi+2]:
        func(s+c, i+1)

func("a", 1)

Submission status: Accepted

Solution code:
def main():
    N = int(input())
    ans = ['a']
    i = 0
    while i != N-1:
        tmp = set()
        i += 1
        for j in range(len(ans)):
            for k in range(i+1):
                tmp.add(ans[j]+chr(97+k))
                if chr(97+k) not in ans[j]:
                    break
        ans = list(tmp)
    ans.sort()
    for a in ans:
        print(a)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import copy

N = int(input())
w  = [['a']]
for n in range(1,N):
    nw = [[] for _ in range(n+1)]
    for i in range(n):
        nw[i] += [x+chr(97+j) for j in range(i+1) for x in w[i]]
        nw[i+1] += [x+chr(97+i+1) for x in w[i]]
    w = copy.deepcopy(nw)

ans = []
for i in range(N):
    ans += [x for x in w[i]]
for x in sorted(ans):
    print(x)

Submission status: Accepted

Solution code:
import copy
N=int(input())
ans = [0]

if N > 1:
  ans1 = []
  a = max(ans)+1
  for i in range(a+1):
    c = copy.copy(ans)
    c.append(i)
    ans1.append(c)
    
if N > 2:
  ans2 = []
  for j in range(len(ans1)):
    a = max(ans1[j])+1
    for i in range(a+1):
      c = copy.copy(ans1[j])
      c.append(i)
      ans2.append(c)

if N > 3:
  ans3 = []
  for j in range(len(ans2)):
    a = max(ans2[j])+1
    for i in range(a+1):
      c = copy.copy(ans2[j])
      c.append(i)
      ans3.append(c)
      

if N > 4:
  ans4 = []
  for j in range(len(ans3)):
    a = max(ans3[j])+1
    for i in range(a+1):
      c = copy.copy(ans3[j])
      c.append(i)
      ans4.append(c)


if N > 5:
  ans5 = []
  for j in range(len(ans4)):
    a = max(ans4[j])+1
    for i in range(a+1):
      c = copy.copy(ans4[j])
      c.append(i)
      ans5.append(c)

      
if N > 6:
  ans6 = []
  for j in range(len(ans5)):
    a = max(ans5[j])+1
    for i in range(a+1):
      c = copy.copy(ans5[j])
      c.append(i)
      ans6.append(c)

if N > 7:
  ans7 = []
  for j in range(len(ans6)):
    a = max(ans6[j])+1
    for i in range(a+1):
      c = copy.copy(ans6[j])
      c.append(i)
      ans7.append(c)

if N > 8:
  ans8 = []
  for j in range(len(ans7)):
    a = max(ans7[j])+1
    for i in range(a+1):
      c = copy.copy(ans7[j])
      c.append(i)
      ans8.append(c)

if N > 9:
  ans9 = []
  for j in range(len(ans8)):
    a = max(ans8[j])+1
    for i in range(a+1):
      c = copy.copy(ans8[j])
      c.append(i)
      ans9.append(c)
      
aaa = "abcdefghij"
if N == 1:
  print("a")    
    
elif N ==2:
  for i in ans1:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)
  
elif N ==3:
  for i in ans2:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)
  
elif N ==4:
  for i in ans3:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)
  
elif N ==5:
  for i in ans4:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)
  
elif N ==6:
  for i in ans5:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)
  
elif N ==7:
  for i in ans6:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)
  
elif N ==8:
  for i in ans7:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)
  
elif N ==9:
  for i in ans8:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)
    
elif N ==10:
  ans9.sort()
  for i in ans9:
    S = ""
    for j in i:
      S = S + aaa[j]
    print(S)

Submission status: Accepted

Solution code:
N = int(input())
s = [[] for i in range(N)]

s[0].append("a")

def maxs(ss):
    max_ss = 0
    for i in range(len(ss)):
        max_ss = max(max_ss,ord(ss[i]))
    return max_ss

for i in range(1,N):
    for ss in s[i-1]:
        for j in range(97,maxs(ss)+2):
            s[i].append(ss+chr(j))

for ss in s[N-1]:
    print(ss)

Submission status: Accepted

Solution code:
n = int(input())
r = 'a',
for _ in range(n - 1):
  r = [s + c for s in r for c in set(s + chr(ord(max(s)) + 1))]
print(*sorted(r), sep='\n')

Submission status: Accepted

Solution code:
N=int(input())
ans = []
def same(c):
    if len(c)==N:
        ans.append(c)
        return
    else:
        for i in range(ord('a'),ord('a')+len(list(set(list(c))))+1):
            same(c+chr(i))

same('a')
for i in ans:
    print(i)

Submission status: Accepted

Solution code:
import sys
input = lambda: sys.stdin.readline().rstrip()
input_nums = lambda: list(map(int, input().split()))
from collections import deque
N = int(input())

s = 'a'
queue = deque()
queue.append(s)
while True:
    a = queue.popleft()
    if len(a) == N:
        queue.append(a)
        break
    origin = a
    a = max(a)
    s = 'a'
    end = chr(ord(a)+2)
    while s != end:
        queue.append(origin+s)
        s = chr(ord(s)+1)
ans = []
while queue:
    ans.append(queue.popleft())
for s in sorted(ans):
    print(s)

Submission status: Accepted

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

al = ['a', 'b', 'c' , 'd', 'e', 'f', 'g', 'h', 'i', 'j']
list = []
for i in range(n):
    new = []
    if i ==0:
        new.append(al[0])
    else:
        lis = copy.deepcopy(list)
        for x in lis:
            flag = False
            for y in al[:i+1]:
                if y in x:
                    new.append(x+y)
                else:
                    if flag == False:
                        new.append(x+y)
                        flag = True
    list = new

for x in new:
    print(x)

Submission status: Accepted

Solution code:
n = int(input())
r = 'a',
for _ in range(n - 1):
  r = {s + c for s in r for c in s + chr(ord(max(s)) + 1)}
print(*sorted(r), sep='\n')

Submission status: Accepted

Solution code:
n=int(input())

al=["a","b","c","d","e","f","g","h","i","j"]

if n==1:
    print("a")
    exit()

#桁数がi
"""
[
    [[a]]
    [[aa],[ab]]
    [[aaa],[aba,abb],[abc]]
]


"""
result=[["a"]]
for i in range(n-1):
    temp=[]
    for item in result[i]:
        uniqAl=len(''.join(set(item)))
        for alp in al[:uniqAl+1]:
            temp.append(item+alp)
    result.append(temp)


for item in result[-1]:
    print(item)

Submission status: Accepted

Solution code:
N = int(input())
Alphabet = ['a','b','c','d','e','f','g','h','i','j']
L = []

for l in range(N):
    if l == 0:
        L.append(['a'])
    else:
        applist = []
        for content in L[l-1]:
            ind = 0
            for j in range(len(content)):
                ind = max(ind,Alphabet.index(content[j]))
            for i in range(ind+2):
                applist.append(content+Alphabet[i])
        L.append(applist)

for content in L[N-1]:
    print(content)

Submission status: Accepted

Solution code:
import sys
stdin = sys.stdin
sys.setrecursionlimit(10**9)
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
nn = lambda: list(stdin.readline().split())
ns = lambda: stdin.readline().rstrip()

al = ['a','b','c','d','e','f','g','h','i','j']

import copy
n = ni()

def f(a,b,m):
  if a == n:
    print(''.join([al[i] for i in b]))
  else:
    for i in range(m+2):
      c = copy.copy(b)
      c.append(i)
      f(a+1,c,max(m,i))

f(1,[0],0)

Submission status: Accepted

Solution code:
from collections import defaultdict
import string
import sys
sys.setrecursionlimit(10 ** 7)
from functools import lru_cache

N = int(input())
alph = string.ascii_lowercase

ans = defaultdict(int)

@lru_cache(maxsize=None)
def search(S, nums):
    if nums in ans:
        return
    if len(nums) == N:
        ans[nums] = S
        return

    for i in range(len(nums)):
        for s, n in zip(S, nums):
            if n == i:
                search(S + s, nums + (n, ))
                break
    C = set(list(S))
    for s in alph:
        if not s in C:
            search(S + s, nums + (len(nums), ))
            break

search('a', (0, ))
ans = list(ans.values())
ans.sort()
print(*ans, sep='\n')

Submission status: Accepted

Solution code:
d = ['','a','b','c','d','e','f','g','h','i','j']
N = int(input())
if N == 1:
  print("a")
elif N == 2:
  print("aa")
  print("ab")
else:
  ans = [[[]]for _ in range(N - 1)]
  ans[0][0] = [1]
  ans[1][0] = [1,1]
  ans[1].append([1,2])
  ansstr = []
  for i in range(N -2):
    for i2 in range(len(ans[i + 1])):
      for i3 in range(max(ans[i + 1][i2]) + 1):
        if i == N - 3:
          ansstr.clear()
          for i4 in range(N - 1):
            ansstr.append(d[ans[i + 1][i2][i4]])
          ansstr.append(d[i3 + 1])
          print("".join(ansstr))
        else:
          ans[i + 2].append(ans[i + 1][i2] + [i3 + 1])
    if i < N - 3:
      ans[i + 2].pop(0)

Submission status: Accepted

Solution code:
d = ['','a','b','c','d','e','f','g','h','i','j']
N = int(input())
if N == 1:
  print("a")
elif N == 2:
  print("aa")
  print("ab")
else:
  ans = [[[]]for _ in range(N - 1)]
  ans[0][0] = [1]
  ans[1][0] = [1,1]
  ans[1].append([1,2])
  ansstr = []
  for i in range(N -2):
    for i2 in range(len(ans[i + 1])):
      for i3 in range(max(ans[i + 1][i2]) + 1):
        if i == N - 3:
          ansstr.clear()
          for i4 in range(N - 1):
            ansstr.append(d[ans[i + 1][i2][i4]])
          ansstr.append(d[i3 + 1])
          print("".join(ansstr))
        else:
          ans[i + 2].append(ans[i + 1][i2] + [i3 + 1])
    if i < N - 3:
      ans[i + 2].pop(0)

Submission status: Accepted

Solution code:
from string import ascii_lowercase
def main():
    n=int(input())
    Ans=['a']
    A=ascii_lowercase
    for i in range(n-1):
        Tmp=[]
        for a in Ans:
            s=set(list(a))
            for l in A:
                Tmp.append(a+l)
                if l not in s:
                    break
        Ans=Tmp[:]
    for ans in Ans:
        print(ans)
    
if __name__=='__main__':
    main()

Submission status: Accepted

Solution code:
N = int(input())-1

dic={}
ans=[]
#N=1
dic['a']=1
ans.append('a')

alp = ['a','b','c','d','e','f','g','h','i','j','k']


for i in range(N):
    ans_temp = ans
    dic_temp = dic
    #init for N
    ans = []
    dic={}
    dic_count={}
    #left a
    for j in ans_temp:
        new_j = 'a'+ j
        ans.append(new_j)
        dic[new_j]=dic_temp[j]
        dic_count[new_j]=1
    # right append
    for l in ans_temp:
        num_alp = dic_temp[l]
        for m in range(num_alp+1):
            new_l = l+alp[m]

            if dic_count.get(new_l) is None:
                ans.append(new_l)
                dic_count[new_j]=1
                if m==num_alp:
                    dic[new_l]=dic_temp[l]+1
                else:
                    dic[new_l]=dic_temp[l]

        
    
        
        

for i in ans:
    print(i)

Submission status: Accepted

Solution code:
import sys
import itertools
import math
from collections import deque
MAX_INT = int(10e15)
MIN_INT = -MAX_INT
mod = 1000000007
sys.setrecursionlimit(1000000)
def IL(): return list(map(int,input().split()))
def SL(): return input().split()
def I(): return int(sys.stdin.readline())
def S(): return input()

#max(chr(ord("z")+1), 
def tami(re,res,cnt,ma):
  if cnt == N:
    ans.append(res)
    return
  for i in range(ord("a"), ma+2):
    tami(chr(i),res+chr(i),cnt+1,max(ma, i))

N = I()

ans = []
tami(chr(ord("a")-1),"",0,ord("a")-1)
ans.sort()
for i in ans:
  print(i)

Submission status: Accepted

Solution code:
# coding: utf-8
import re
import math
import itertools
from copy import deepcopy
import fractions
import random
from heapq import heappop,heappush
import time
import os
import sys
import datetime
from functools import lru_cache
readline=readline = sys.stdin.readline
sys.setrecursionlimit(2000)
#import numpy as np
alphabet="abcdefghijklmnopqrstuvwxyz"
mod=int(10**9+7)
inf=int(10**20)
def yn(b):
    if b:
        print("yes")
    else:
        print("no")
def Yn(b):
    if b:
        print("Yes")
    else:
        print("No")
def YN(b):
    if b:
        print("YES")
    else:
        print("NO")
class union_find():
    def __init__(self,n):
        self.n=n
        self.P=[a for a in range(N)]
        self.rank=[0]*n
 
    def find(self,x):
        if(x!=self.P[x]):self.P[x]=self.find(self.P[x])
        return self.P[x]
 
    def same(self,x,y):
        return self.find(x)==self.find(y)
 
    def link(self,x,y):
        if self.rank[x]<self.rank[y]:
            self.P[x]=y
        elif self.rank[y]<self.rank[x]:
            self.P[y]=x
        else:
            self.P[x]=y
            self.rank[y]+=1
 
    def unite(self,x,y):
        self.link(self.find(x),self.find(y))
 
    def size(self):
        S=set()
        for a in range(self.n):
            S.add(self.find(a))
        return len(S)
def bin_(num,size):
    A=[0]*size
    for a in range(size):
        if (num>>(size-a-1))&1==1:
            A[a]=1
        else:
            A[a]=0
    return A
def fac_list(n,mod_=0):
    A=[1]*(n+1)
    for a in range(2,len(A)):
        A[a]=A[a-1]*a
        if(mod>0):A[a]%=mod_
    return A
def comb(n,r,mod,fac):
    if(n-r<0):return 0
    return (fac[n]*pow(fac[n-r],mod-2,mod)*pow(fac[r],mod-2,mod))%mod
def next_comb(num,size):
    x=num&(-num)
    y=num+x
    z=num&(~y)
    z//=x
    z=z>>1
    num=(y|z)
    if(num>=(1<<size)):return False
    else:
        return num
def get_primes(n,type="int"):
    A=[True]*(n+1)
    A[0]=False
    A[1]=False
    for a in range(2,n+1):
        if A[a]:
            for b in range(a*2,n+1,a):
                A[b]=False
    if(type=="bool"):return A
    B=[]
    for a in range(n+1):
        if(A[a]):B.append(a)
    return B
def is_prime(num):
    if(num<=2):return False
    i=2
    while i*i<=num:
       if(num%i==0):return False
       i+=1
    return True


def join(A,c=" "):
    n=len(A)
    A=list(map(str,A))
    s=""
    for a in range(n):
        s+=A[a]
        if(a<n-1):s+=c
    return s
ans=[]
def f(s,N):
    if(len(s)==N):
        ans.append(s)
        return
    max_=-1
    for a in s:
        max_=max(max_,ord(a)-ord("a"))
    for a in range(max_+2):
        s1=s+chr(ord(chr(max_+ord("a")))-a+1)
        f(s1,N)

#main
N=int(input())
ans=[]
if N==1:
    print("a")
else:
    f("a",N)
    ans.sort()
    print("\n".join(ans))

Submission status: Accepted

Solution code:
C = 'abcdefghijklmnopqrstuvwxyz'
N = int(input())
def dfs(s):
  l = len(s)
  if l >= N:
    print(s)
    return
  for i in range(l+1):
    if len(set(s)) < i:
      continue
    dfs(s+C[i])
dfs('')

Submission status: Accepted

Solution code:
N = int(input())

def standard(n, cur):
  if n == 0:
    print(''.join(cur))
  else:
    newC = chr(ord(sorted(cur)[-1]) + 1)
    for c in sorted(set(cur + [newC])):
      standard(n - 1, cur + [c])

standard(N - 1, ['a'])

Submission status: Accepted

Solution code:
N = int(input())
#N = 4
def to_str(n):
    s = [chr(i + 97) for i in reversed(n)]
    s = "".join(s)
    return s
n = [0] * N
n_max = list(reversed(list(range(N))))

s = to_str(n)
print(s)
while True:
    for j in range(N-1):
        #if n[j] < n[j+1]+1:
        if n[j] < max(n[j+1:]) + 1:
            n[j] += 1
            for k in range(j):
                n[k] = 0
            s = to_str(n)
            print(s)
            break
    if n == n_max:
        break

Submission status: Accepted

Solution code:
import copy

n = int(input())

l = ['a']
ans = []


def f(n, s, l):
    if n == 1:
        for c in l:
            ans.append(s+c)
        return

    n -= 1
    for c in l:
        if (s+c).count(l[-1]) == 0:
            f(n, s+c, l)
        else:
            ll = copy.deepcopy(l)
            ll.append(chr(ord(ll[-1])+1))
            f(n, s+c, ll)


f(n, "", l)
for ss in ans:
    print(ss)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10**6)
N = int(input())

s = 'abcdefghijklmn'

ans = []
def f(t, k, n):
    if n == N:
        ans.append(t)
        return
    for i in range(k+1):
        f(t+s[i], max(k,i+1), n+1)

f('a', 1, 1)

for a in ans:
    print(a)

Submission status: Accepted

Solution code:
alpha = "abcdefghij"
n=int(input())
patterns = ["a"]
for _ in range(n-1):
    last_patterns = patterns.copy()
    patterns = []
    for string in last_patterns:
        useful_str = alpha[:len(set(string))+1]
        for str_ in useful_str:
            patterns.append(string + str_)

for pat in patterns:
    print(pat)

Submission status: Accepted

Solution code:
N = int(input())
a = [[[0]]]
k = 0
while k < N-1:
  c = a[k]
  a.append([])
  for r in c:
    for i in range(max(r)+2):
      x = r + [i]
      a[k+1].append(x)
  
  k += 1
A = a[-1]
for s in A:
  ans = ""
  for i in range(N):
    ans += chr(s[i]+97)
  print(ans)