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())
o=ord('a')

def dfs(s,m):
    if len(s)==n:
        print(s)
    else:
        for i in range(m+1):
            dfs(s+chr(o+i),max(m,i+1))
dfs("",0)

Submission status: Accepted

Solution code:
def dfs(word, i):
    if len(word) == n:
        print(word)
    else:
        if i == 0:
            dfs('a', 1)
        else:
            for j in range(len(set(word)) + 1):
                dfs(word + chr(97 + j), j + 1)


if __name__ == "__main__":
    n = int(input())

    dfs('', 0)

Submission status: Accepted

Solution code:
N = int(input())
str = "abcdefghijklmnopqrstuvwxyz"
def dfs(s,mx):
    if len(s) == N:
        print(s)
    else:
        for c in str[:mx+1]:
            if c == str[mx]: dfs(s+c, mx+1)
            else: dfs(s+c, mx)
dfs("", 0)

Submission status: Accepted

Solution code:
def dfs(s, mx, N):
    if len(s) == N:
        print s
    else:
        for ch in range(ord('a'), ord(mx) + 1):
            if chr(ch) == mx:
                dfs(s + chr(ch), chr(ord(mx) + 1), N)
            else:
                dfs(s + chr(ch), mx, N)

def solve2():
    N = int(raw_input())
    dfs('', 'a', N)

if __name__ == '__main__':
    solve2()

Submission status: Accepted

Solution code:
import sys
import string
input = sys.stdin.readline

N = int(input())

ans = ['a']
alph = list(string.ascii_lowercase[:10])
l = 1

while l < N:
    ans2 = []
    for value in ans:
        for letter in alph:
            ans2.append(value + letter)
            if letter not in value:
                break
    l += 1
    ans = ans2
    
for value in sorted(ans):
    print(value)

Submission status: Accepted

Solution code:
# from math import factorial,sqrt
# from itertools import permutations as permus
# from fractions import gcd
# from collections import deque,Counter

# import numpy as np
# import scipy as scp

# 入力の受け取り
n = int(input())

strlist = "abcdefghij"

def dfs(s,num):
    if len(s) >= n:
        print(s)
        return
    elif num ==0:
        dfs("a",1)
    else:
        for i in range(num):
            dfs(s+strlist[i],num)
        dfs(s+strlist[num],num+1)

dfs("",0)

Submission status: Accepted

Solution code:
"""
N = 2, 3, 4,...と実験していくと何となく再帰的な構造が見える。
ここで文字列の末尾に再帰構造を見出そうとするときれいにいかず失敗する。
（例）
    N = 3                   N = 4
    a---a---a               a---a---a---a
    '   '---b               '   '   '---b
    '---b---a               '   '---b---a
        '---b               '       '---b
        '---c               '       '---c
                            '---b---a---a
                                '   '---b
                                '   '---c
                                '---b---a
                                '   '---b
                                '   '---c
                                '---c---a
                                    '---b
                                    '---c
                                    '---d

正しくは先頭から再帰構造を見出すべき（数学的帰納法を先頭にかけるのと似た感じ。。。）
するとN=4の場合の樹形図の左から３列目まではN=3と全く同じ形なことに気づく。

よって左から木を生やしていき、（根から葉まで使われた文字数）＋１が新しい葉として生じる。

ここで実際に木を構成するのは面倒そうなので、実装時にはNの各値に対して
（根から葉までの文字列＋使われた最後位の文字）の組をリストに格納する。
（例）N=4なら
    [("aaaa", "a"), ("aaab", "b"), ("aaba", "b"), ("aabb", "b"), ("aabc", "c"), ("abaa", "b"),...]
各組をpopleftすれば、それから新しい文字列（新しい葉）が構成可能。
"""

from collections import deque

N = int(input())
leaf = deque([("a", "a")])
newleaf = []
for _ in range(N - 1):
    while leaf:
        string, maxchar = leaf.popleft()
        maxnum = ord(maxchar) # maxcharをASCIIコードに変換
        for i in range(97, maxnum + 2):
            newleaf.append((string + chr(i), chr(max(maxnum, i))))
    leaf = deque(newleaf)
    newleaf = []

for s in leaf:
    print(s[0])

Submission status: Accepted

Solution code:
N = int(input())


def f(L, m):
    l = len(L)
    if l == N:
        print(''.join(list(map(lambda i: chr(i + 96), L))))
        return
    for d in range(1, min(l + 1, m + 1) + 1):
        f(L + [d], max(m, d))


f([1], 1)

Submission status: Accepted

Solution code:
import sys
import copy
input = sys.stdin.readline

N = int(input())

if N == 1:
    print('a')
    exit()
if N == 2:
    print('aa')
    print('ab')
    exit()

ans = ['aaa', 'aab', 'aba', 'abb', 'abc']
alph = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
length = 3

while length < N:
    ans2 = []
    for value in ans:
        for letter in alph:
            ans2.append(value + letter)
            if letter not in value:
                break
    length += 1
    ans = copy.deepcopy(sorted(ans2))

for value in ans:
    print(value)

Submission status: Accepted

Solution code:
from collections import deque
N=int(input())
if N==1:
    print("a")
    exit()
X=[chr(i+97) for i in range(N)]
q=deque(["a"])
while(len(q)>0):
    r=q.popleft()
    k=len(set(r))
    for i in range(k+1):
        p=r+X[i]
        if len(p)==N:
            print(p)
        else:
            q.append(p)

Submission status: Accepted

Solution code:
n=int(input())
def dfs(s,st):
  if len(s)==n:
    return print(s)
  else:
    for i in range(ord('a'),ord(st)+1):
      if i==ord(st):
        dfs(s+chr(i),chr(ord(st)+1))
      else:
        dfs(s+chr(i),chr(ord(st)))
dfs('','a')

Submission status: Accepted

Solution code:
N = int(input())


def f(L):
    l = len(L)
    if l == N:
        print(''.join(list(map(lambda i: chr(i + 96), L))))
        return
    for d in range(1, min(l, max(L)) + 2):
        f(L + [d])


f([1])

Submission status: Accepted

Solution code:
n = int(input())


def dfs(s, mx):
    if len(s) == n:
        print(s)
        return
    for i in range(ord('a'), ord(mx) + 2):
        dfs(s + chr(i), max(mx, chr(i)))


dfs('a', 'a')

Submission status: Accepted

Solution code:
# import bisect
# # import heapq
# # from copy import deepcopy
# # from collections import deque
# # from collections import Counter
# # from itertools import accumulate
# # from itertools import permutations
# import numpy as np
# # import math
# a,b,c = map(int, input().split())
n = int(input())
# p = list(map(int, input().split()))


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

        dfs(s+chr(ord('a')+var), var+1)

dfs('a',1)

Submission status: Accepted

Solution code:
n=int(input())
def cur(x):
    if len(x)==n:
        s="".join([chr( ord("a")+x[i]) for i in range(n)])
        print(s)

    else:
         for i in range(max(x)+2):
             cur(x+[i])

cur([0])

Submission status: Accepted

Solution code:
n = int(input())

abc = list('abcdefghij')


def solve(ans):
    if len(ans) == n:
        print(*ans, sep='')
    else:
        idx = max([abc.index(ans[i]) for i in range(len(ans))])
        for i in range(idx+2):
            nans = ans + [abc[i]]
            solve(nans)


solve(['a'])

Submission status: Accepted

Solution code:
def dfs(n, s, types):
    if(n==1):
        for i in range(types):
            c = chr(97+i)
            print(s+c)
    else:
        for i in range(types):
            c = chr(97+i)
            if(i==types-1):
                dfs(n-1, s+c, types+1)
            else:
                dfs(n-1, s+c, types)

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

Submission status: Accepted

Solution code:
abc = "abcdefghij"

N = int(input())

def dfs(S, i):
    if len(S) == N:
        return S + "\n"

    res = ""
    for c in abc[:i]:
        res += dfs(S + c, i)
    res += dfs(S + abc[i], i + 1)

    return res

print(dfs("", 0))

Submission status: Accepted

Solution code:
def main():
    n = int(input())
    def dfs(s, c):
        chars = 'abcdefghijklmnop'
        if len(s) == n:
            print(s)
            return
        for i in range(c):
            dfs(s+chars[i], c)
        dfs(s+chars[c], c+1)
    dfs("", 0)

main()

Submission status: Accepted

Solution code:
n = int(input())

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

ans = []


def dfs(s, c):
    for i in range(ord('a'), ord(c) + 2):
        now = s + chr(i)
        if len(now) == n:
            ans.append(now)
        elif i > ord(c):
            dfs(now, chr(i))
        else:
            dfs(now, c)


dfs('a', 'a')

for c in ans:
    print(c)

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:
def solve(n, s, mx):
    # print(n, s, mx)
    if n == 0:
        print(s)
    else:
        for i in range(mx):
            solve(n - 1, s + chr(ord("a") + i), max(mx, i + 2))

n = int(input())
solve(n - 1, 'a', 2)

Submission status: Accepted

Solution code:
def f(word,N):
    if len(word)==n:
        return print(word)
    else:
        for i in range(N+1):
            f(word+chr(97+i),N+1 if i==N else N)


n=int(input())
f("",0)

Submission status: Accepted

Solution code:
def DFS(word,N):
    if len(word)==n:
        return print(word)
    else:
        for i in range(N+1):
            DFS(word+chr(97+i),N+1 if i==N else N)


n=int(input())
DFS("",0)

Submission status: Accepted

Solution code:
from collections import deque
N = int(input())

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
unvisited = deque(alphabet[0 : N])
visited = deque()
st = deque([["a", visited, unvisited]]) # stack

while len(st) > 0:
    str, visited, unvisited = st.popleft()

    if str[-1] not in visited:
        visited.append(str[-1])
        unvisited.popleft()

    if len(str) == N:
        print(str)
    else:
        # すでに使った文字を使う
        for x in visited:
            st.append([str + x, deque(visited), deque(unvisited)])
        # まだ使っていない文字を使う
        if len(unvisited) > 0:
            x = unvisited[0]
            st.append([str + x, deque(visited), deque(unvisited)])

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7 # 998244353
input=lambda:sys.stdin.readline().rstrip()
def resolve():
    n = int(input())
    n -= 1
    now = ['a']
    for _ in range(n):
        next = []
        for S in now:
            d = ord(max(S)) - ord('a')
            for i in range(d+2):
                next.append(S + chr(i + ord('a')))
        now = next

    now.sort()
    for S in now:
        print(S)
resolve()

Submission status: Accepted

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

    chars_list = ['a']
    a = 'abcdefghij'

    while n - 1 > 0:
        new_list = []
        for char in chars_list:
            for alphabet in a:
                new_list.append(char + alphabet)
                if alphabet not in char:
                    break
        chars_list = copy.deepcopy(new_list)
        n -= 1

    print('\n'.join(chars_list))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
dic={0:'a',1:'b',2:'c',3:'d',4:'e',5:'f',6:'g',7:'h',8:'i',9:'j'}
ans=[['a',1]]
for i in range(1,n):
  tmp=[]
  for prev,val in ans:
    for j in range(val+1):
      if j!=val:
        tmp.append([prev+dic[j],val])
      else:
        tmp.append([prev+dic[j],val+1])
  ans=tmp
ans=sorted(ans,key=lambda x:x[0])
for i in range(len(ans)):
  print(ans[i][0])

Submission status: Accepted

Solution code:
n=int(input())
def b(s):
  if len(s)==n:
    print(s)
    return
  for i in "abcdefghijklmnopqrstuvwxyz":
    b(s+i)
    if max(list(s))==chr(ord(i)-1):return
b("a")

Submission status: Accepted

Solution code:
n = int(input())
candidate = ['a']


def dfs(s, c):
    if len(s) == n:
        return
    for i in range(ord('a'), ord(c) + 2):
        now = s + chr(i)
        candidate.append(now)
        if i > ord(c):
            dfs(now, chr(i))
        else:
            dfs(now, c)


dfs('a', 'a')

for c in candidate:
    if len(c) == n:
        print(c)

Submission status: Accepted

Solution code:
N = int(input())

A = [chr(ord("a") + i) for i in range(26)]


def dfs(S, i):
    if len(S) == N:
        print(S)
        return
    for j in range(i):
        dfs(S + A[j], i)
    dfs(S + A[i], i + 1)


dfs("", 0)

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-
ALPHABET = ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j")


def f(num, n, s):
    if n == num:
        for _s in sorted(s):
            print(_s)
        return
    else:
        tmp = []
        for i, _s in enumerate(s):
            pre_last_index = ALPHABET.index(sorted(tuple(_s))[-1])
            for al in ALPHABET[:pre_last_index + 2]:
                tmp.append(_s + al)
        f(num + 1, n, tmp)



def main():
    n = int(input())
    f(1, n, ["a"])


if __name__ == '__main__':
    main()

Submission status: Accepted

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

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

    for c in string.ascii_lowercase[:i + 1]:
        if c == string.ascii_lowercase[i]:
            rec(s + c, i + 1)
        else:
            rec(s + c, i)

rec("a", 1)
for x in ans:
    print(x)

Submission status: Accepted

Solution code:
N = int(input())

lst = []

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


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

    for k in range(i):
        dfs(s + d[k], i)

    dfs(s+d[i], i + 1)


dfs('', 0)

Submission status: Accepted

Solution code:
n=int(input())
s='abcdefghijklmnopqrstuvwxyz'
bottom=[[] for i in range(10)]
bottom[0]=['a']

def solve(n):
    num=0
    while num<n:
        num=num+1
        for base in bottom[num-1]:
            for i in s[:num+1]:
                if i!='a' and chr(ord(i)-1) not in base:break
                bottom[num].append(base+i)

solve(n-1)
#print(*bottom[n-2])
print(*bottom[n-1],sep='\n')

Submission status: Accepted

Solution code:
N = int(input())
from collections import deque
import itertools
ans = deque()
l = []
r = deque()
for i in range(N):
  l.append(chr(97+i))
  r.append(l.copy())
  

p = [[[] for _ in range(N)] for _ in range(N)]
p[0][0].append('a')
for i in range(1,N):
  for j in r[i]:
    x = ord(j)-97
    for n,k in enumerate(p[i-1][max(0,x-1):],max(0,x-1)):
      for m in k:
        p[i][max(n,x)].append(m+j)


p = p[-1]
p = list(itertools.chain.from_iterable(p))
p.sort()
for q in p:
  print(q)

Submission status: Accepted

Solution code:
N = int(input())
mojis = ["a","b","c","d","e","f","g","h","i","j"]
def append_m(moji):
    arr = []
    for i in mojis[:len(set(moji))+1]:
        arr.append(moji+i)
    return arr

arr = ["a"]
for i in range(N-1):
    tmp = []
    for j in arr:
        tmp += append_m(j)
    arr = tmp
for i in arr:
    print(i)

Submission status: Accepted

Solution code:
import sys
input=lambda: sys.stdin.readline().rstrip()
n=int(input())
A=[chr(97+int(i)) for i in range(n)]

Ans=["a"]
if n>=2:
  for _ in range(n-1):
    Ans2=[]
    for a in Ans:
      s=set()
      for aa in a:
        s.add(aa)
      ss=len(s)
      for i in range(ss+1):
        Ans2.append(a+A[i])
    Ans=Ans2
Ans.sort()
for ans in Ans:
  print(ans)

Submission status: Accepted

Solution code:
def DFS(word,n):
  if len(word)==N:
    return print(word)
  else:
    for i in range(n+1):
      if i==0 :
        DFS(word+chr(97+i),n+1)
      elif chr(97+i-1) in word:
        DFS(word+chr(97+i),n+1)

N=int(input())
DFS('',0)

Submission status: Accepted

Solution code:
N = int(input())
from collections import deque
import itertools
ans = deque()
l = []
r = deque()
for i in range(N):
  l.append(chr(97+i))
  r.append(l.copy())
  

p = [[[] for _ in range(N)] for _ in range(N)]
p[0][0].append('a')
for i in range(1,N):
  for j in r[i]:
    x = ord(j)-97
    for n,k in enumerate(p[i-1][max(0,x-1):],max(0,x-1)):
      for m in k:
        p[i][max(n,x)].append(m+j)


p = p[-1]
p = list(itertools.chain.from_iterable(p))
p = sorted(p)
for q in p:
  print(q)

Submission status: Accepted

Solution code:
n = int(input())
alp = ["a","b","c","d","e","f","g","h","i","j"]
ans = []
cnt = 0
def dfs_rec(prev,cnt): # prev は前までの文字列 cntは文字種数を持つ
    if len(prev) == n:
        ans.append("".join(prev))
        return
    for i in range(cnt+1):
        dfs_rec(prev+[alp[i]],cnt+(i//cnt)) # この再帰呼び出しの際にprevが書き換わる？


dfs_rec(["a"],1)
ans.sort()
for s in ans:
    print(s)

Submission status: Accepted

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

def dfs(s, n, m):
    if n > N:
        print(''.join([chr(ss) for ss in s]))
        return True
    for ns in range(97, m+2):
        s[n-1] = ns
        dfs(s, n+1, max(m, ns))

s = [0] * N
dfs(s, 1, 96)

Submission status: Accepted

Solution code:
def ansstr(s,n,c):
    if len(s)==n:
        print(s)
    else:
        for i in range(c+1):
            a=0
            ch=chr(ord('a')+i)
            if i==c:
                a=1
            ansstr(s+ch,n,c+a)
    
    
n=int(input())
ansstr("a",n,1)

Submission status: Accepted

Solution code:
N = int(input())
# 1<=N<=10 abcdefghij
L = "abcdefghijk"[:N+1]

def dfs(s,mx):
    M = L.index(mx)
    if len(s) == N:
        print(s)
    else:
        for i in range(M+1):
            if L[i] == mx:
                dfs(s + L[i],L[M+1])
            else:
                dfs(s + L[i],mx)

dfs("",'a')

Submission status: Accepted

Solution code:
n = int(input())
q = ['a']
for i in range(n-1):
   nq = []
   for s in q:
      stop = ord(max(s)) + 2
      for i in range(ord('a'), stop):
         nq.append(s + chr(i))
   q = nq

for s in q:
   print(s)

Submission status: Accepted

Solution code:
#!python3

iim = lambda: map(int, input().rstrip().split())
from collections import deque

def resolve():
    N = int(input())
    S = tuple("abcdefghij")

    q = deque([("", 0, 0)])
    ans = []
    while q:
        #print(q)
        s1, i1, i2 = q.popleft()
        #print(s1, i1, i2)

        if i1 == N:
            ans.append(s1)
            continue
        for i in range(i2):
            q.append((s1+S[i], i1+1, i2))
        q.append((s1+S[i2], i1+1, i2+1))

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


if __name__ == "__main__":
    resolve()

Submission status: Accepted

Solution code:
n = int(input())
s = [('', 0)]
cnt = 0
ans = []
while s:
    t, k = s.pop()
    if len(t) == n:
        print(t)
    else:
        s.append((t + chr(k + 97), k + 1))
        for i in range(k - 1, -1, -1):
            s.append((t + chr(i + 97), k))

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
'''
old_stack=deque(['a'])
while old_stack:
    s=old_stack.popleft()
    if len(s)==n:
        old_stack.appendleft(s)
        break
    for i in range(ord(max(s))-ord('a')+2):
        old_stack.append(s+chr(ord('a')+i))

for o in old_stack:    
    print(o)
'''
import copy
stack=deque([[0]])
while stack:
    s=stack.popleft()
    if len(s)==n:
        stack.appendleft(s)
        break
    for i in range(max(s)+2):
        news=copy.deepcopy(s)
        news.append(i)
        stack.append(news)

while stack:
    x=''
    s=stack.popleft()
    for i in range(len(s)):
        s[i]=chr(ord('a')+s[i])
    print(''.join(s))

Submission status: Accepted

Solution code:
import sys
import numpy as np
from itertools import combinations


def input():
    return sys.stdin.readline()[:-1]


if __name__ == "__main__":
    N = int(input())
    al = [chr(ord('a') + i) for i in range(26)]

    def dfs(s, mx):
        if (len(s) == N):
            print(s)
        else:
            for c in al:
                if c == chr(ord(mx) + 1):
                    break
                tmp = chr(ord(mx) + 1) if (c == mx) else mx
                dfs(s+c, tmp)

    dfs('', 'a')

Submission status: Accepted

Solution code:
import string
def dfs(w, d):
    if len(w) == N:
        print(w)
        return
    for i in range(d + 1):
        if i == d:
            dfs(w + wordlst[i], d + 1)
        else:
            dfs(w + wordlst[i], d)

N = int(input())
anslst = []
nlst = [0] * N
wordlst = string.ascii_lowercase
dfs('a', 1)

Submission status: Accepted

Solution code:
N = int(input())
from string import ascii_letters

def dfs(s, mx):
    if len(s) == N:
        print(s)
    else:
        for i, c in enumerate(ascii_letters[:mx]):
            dfs(s + c, mx + 1 if i + 1 == mx else mx)

dfs("", 1)

Submission status: Accepted

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

Ans = [L[0]]
Backup = []

for k in range(N-1):
    Backup = Ans
    Ans = [i+L[j] for i in Backup for j in range(len(set(i))+1)]

for i in Ans:
    print(i)

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(1 << 25)
read = sys.stdin.readline


def read_ints():
    return list(map(int, read().split()))


def read_a_int():
    return int(read())


def read_tuple(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(tuple(map(int, read().split())))
    return ret


def read_col(H, n_cols):
    '''
    H is number of rows
    n_cols is number of cols
    A列、B列が与えられるようなとき
    '''
    ret = [[] for _ in range(n_cols)]
    for _ in range(H):
        tmp = list(map(int, read().split()))
        for col in range(n_cols):
            ret[col].append(tmp[col])
    return ret


def read_matrix(H):
    '''
    H is number of rows
    '''
    ret = []
    for _ in range(H):
        ret.append(list(map(int, read().split())))
    return ret
    # return [list(map(int, read().split())) for _ in range(H)] # 内包表記はpypyでは遅いため


def read_map(H):
    '''
    H is number of rows
    文字列で与えられた盤面を読み取る用
    '''
    return [read()[:-1] for _ in range(H)]


def read_map_as_int(H):
    '''
    #→1,.→0として読み込む
    '''
    ret = []
    for _ in range(H):
        ret.append([1 if s == '#' else 0 for s in read()[:-1]])
        # 内包表記はpypyでは若干遅いことに注意
        # #numpy使うだろうからこれを残しておくけど
    return ret


# default import
from collections import defaultdict, Counter, deque
from operator import itemgetter
from itertools import product, permutations, combinations
from bisect import bisect_left, bisect_right  # , insort_left, insort_right

# 同型→文字数カウントのパターンが同じ
# 標準形→文字数辞書順の最も速いもの


N = read_a_int()


moji = 'abcdefghij'
candi = []
moji = moji[:N]


def dfs(now, i, j):
    # j....いままでで最大の文字のidx
    # 文字を作って返す
    if i == N:
        candi.append(now)
        return
        # return now
    for jj in range(j + 2):
        dfs(now + moji[jj], i + 1, max(j, jj))


dfs('', 0, -1)

print(*sorted(candi), sep='\n')


# for i in range(1, N + 1):  # 何番目まで使うか
#     mojisyu = moji[:i]  # ここで使う文字種類
#     # 文字種類でaを先頭にできるだけ標準形を列挙したい
#     for j in range(1, i):

Submission status: Accepted

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

def f(x):
  A=[]
  for _ in range(n):
    A.append(x%10)
    x//=10
  return A[::-1]

def g(X):
  cur=X[0]
  ret=-1
  for i in range(1,n):
    if X[i]+1<=cur+1 and X[i]+1<=i:
      ret=i
    cur=max(cur,X[i])
  return ret
Ans=[0]

a=f(0)
b=g(a)
while b>=0:
  next=0
  for i in range(n):
    if i<b:
      next+=a[i]*(10**(n-1-i))
    elif i==b:
      next+=(a[i]+1)*(10**(n-1-i))
  Ans.append(next)
  a=f(next)
  b=g(a)
for a in Ans:
  ans=""
  for x in f(a):
    ans+=chr(97+x)
  print(ans)

Submission status: Accepted

Solution code:
def comb(current, mx, target: int):
    if len(current) == target:
        yield current
    elif len(current) < target and len(alphabet) > 0:
        for i in range(mx + 1):
            yield from comb(current + [chr(i + 97)], mx + 1 if i == mx else mx, target)


if __name__ == '__main__':
    n = int(input())
    alphabet = [str(chr(i)) for i in range(97, 97 + 26)]
    result = set()

    for perm in comb([], 0, n):
        print("".join(perm))

Submission status: Accepted

Solution code:
import string
n = int(input())
cs = string.ascii_lowercase
cm = {cs[i]:i for i in range(len(cs))}
t = 1
def rec(st):
    global t
    if (len(st) >= n):
        print(st)
        t += 1
        return 0
    k = max(cm[st[i]]+1 for i in range(len(st)))
    for c in cs[: k + 1]:
        rec(st+c)
    
    
rec('a')

Submission status: Accepted

Solution code:
n = int(input())

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

dfs("", "a")

Submission status: Accepted

Solution code:
import copy
n = int(input())
box = [[] for _ in range(n)]
box[0] = [[0]]
if n == 1:
     print('a')
else:
     for i in range(1,n):
          for j in range(len(box[i-1])):
               for k in range(max(box[i-1][j])+2):
                    a = copy.deepcopy(box[i-1][j])
                    a.extend([k])
                    box[i].extend([a])
     for i in range(len(box[n-1])):
       ans = [''] * n
       for j in range(n):
            ans[j] = chr(ord('a') + box[n-1][i][j])

       print(''.join(ans))

Submission status: Accepted

Solution code:
N=int(input())

S = 'abcdefghij'

def num(x):
    ans = 0
    for i in range(len(S)):
        count = 0
        for j in range(0,len(x)):
            if x[j] == S[i]:
                count = count +1
        if count != 0:
            ans = ans + 1
        else:
            ans = ans
    return ans

def base(x):
    List=[]
    for j in range(len(x)):
        for i in range(num(x[j])+1):
            List.append(x[j]+S[i])
    return List

K = 'a'

cou = 1
while cou < N:
    K = base(K)
    cou = cou+1

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

Submission status: Accepted

Solution code:
from string import ascii_lowercase as al


def dfs(p, i):
    if len(p) == N:
        print("".join(p))
        return
    for j in range(i+1):
        if j == i:
            dfs(p + list(al[j]), i+1)
        else:
            dfs(p + list(al[j]), i)


N = int(input())
dfs([], 0)

Submission status: Accepted

Solution code:
n = int(input())
l = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
a = []
def h(i, s, t):
	if i == 0:
		a.append(s)
		print(s)
	else:
		for j in range(t+1):
			ns = s+l[j]
			nt = max([j+1, t])
			h(i-1, ns, nt)
h(n, "", 0)

Submission status: Accepted

Solution code:
n = int(input())

abc = list('abcdefghijk')


def solve(ans):
    if len(ans) == n:
        print(*ans, sep='')
    else:
        idx = max([abc.index(ans[i]) for i in range(len(ans))])
        for i in range(idx+2):
            nans = ans + [abc[i]]
            solve(nans)


solve(['a'])

Submission status: Accepted

Solution code:
n = int(input())
s=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
x=[j for j in range(n)]
from collections import deque
import copy
old_stack=deque(['a'])
x=1
while old_stack:
    s=old_stack.popleft()
    if len(s)==n:
        old_stack.appendleft(s)
        break
    for i in range(ord(max(s))-ord('a')+2):
        old_stack.append(s+chr(ord('a')+i))

for o in old_stack:    
    print(o)

Submission status: Accepted

Solution code:
N = int(input())

tmp = "abcdefghij"

ans = ""

i = 1


def mkstr(ans, i):
    if len(ans) >= N:
        print(ans)
    else:
        for j in range(i):
            if j == i - 1:
                mkstr(ans + tmp[j], i + 1)
            else:
                mkstr(ans + tmp[j], i)


mkstr(ans, i)

Submission status: Accepted

Solution code:
n = int(input())
ans = []
def dfs(line, mx):
    if len(line) == n:
        ans.append(line)
    else:
        for i in range(mx+1):
            line_copy = line.copy()
            line_copy.append(i)
            dfs(line_copy, mx)
        line_copy = line.copy()
        line_copy.append(mx+1)
        dfs(line_copy, mx+1)

dfs([0], 0)

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

for a in ans:
    for i in a:
        print(figures[i], end="")
    print()

Submission status: Accepted

Solution code:
import sys

sys.setrecursionlimit(10 ** 8)

input = sys.stdin.readline


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

    ans = []

    def solve(s, n):
        if n == N:
            ans.append(s)
            return

        for i in range(len(set(s)) + 1):
            solve(s + (chr(ord('a') + i)), n + 1)

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
n=int(input())
ans=[]
def rec(i,s):
    if i == n:
        print(s)
        return
    else:
        for j in range(len(set(s)) + 1):
            rec(i+1,s+chr(ord("a")+j))
rec(1,"a")

Submission status: Accepted

Solution code:
N = int(input()) # 数字を変数に格納

List = [[] for i in range(N)]

for i in range(N):
    for j in range(i+1):
        List[i].append(chr(97+j))

flag = 0
point = [0]*(N+1)

while flag != 1:
    chars = ''
    i = 0
    while len(chars) < N:
        if i > 0:
            mx = max(point[0:i])
        if i != 0 and mx+1 < point[i]:
            point[i-1] += 1
            point[i] = 0
            break
        chars += List[i][point[i]]
        if i == N-1:
            point[i] += 1
        if point[i] == N:
            flag = 1
        i += 1
    if len(chars) == N:
        print(chars)

Submission status: Accepted

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

def dfs(s, mx, N):
    if len(s) == N:
        print(s)
    else:
        for i in range(97, ord(mx) + 1):
            dfs(s + chr(i), chr(max(i + 1, ord(mx))), N)

N = int(input())

dfs('', 'a', N)

Submission status: Accepted

Solution code:
N = int(input())
s = 'abcdefghij'

def dfs(word, n):
    if len(word)==N:
        print(word)
    else:
        for i in range(n+1):
            dfs(word+s[i], n+1 if i==n else n)
dfs('a', 1)