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:
import sys
from collections import deque

input = sys.stdin.readline


def dfs(N):
    alphabet = "abcdefghij"
    stack = deque(["a"])
    while stack:
        s = stack.pop()
        if len(s) == N:
            print(s)
            continue
        for suffix in reversed(alphabet[:len(set(s)) + 1]):
            stack.append("".join((s, suffix)))


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

    dfs(N)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
import sys
from collections import deque

input = sys.stdin.readline


def dfs(N):
    alphabet = "abcdefghij"
    stack = deque(["a"])
    while stack:
        s = stack.pop()
        if len(s) == N:
            print(s)
            continue
        suffixes = []
        for al in alphabet:
            suffixes.append(al)
            if al not in s:
                break
        for suffix in reversed(suffixes):
            stack.append("".join((s, suffix)))


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

    dfs(N)


if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
ch = ['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']

n = int(input())

import queue
q=queue.Queue()
l = 1
q.put(["a", 0])

while True:
  temp = q.get()
  l=len(temp[0])
  if l==n:
    break
    
  for i in range(temp[1]+2):
    ne = temp[0]+ch[i]
    nn = max(temp[1], i)
    q.put([ne, nn])

print(temp[0])
while not q.empty():
  print(q.get()[0])

Submission status: Accepted

Solution code:
N = int(input())
def dfs(ch, Ma):
    if len(ch) == N:
        print(ch)
        return
    for i in range(97, Ma+2):
        dfs(ch+chr(i), max(Ma, i))
dfs('a', 97)

Submission status: Accepted

Solution code:
#TODO
def dfs(word, idx):
    if len(word)==n:
        print(word)
        return
    for j in range(idx):
        dfs(word+chr(j+mx), idx)
    dfs(word+chr(idx+mx), idx+1)

n = int(input())
mx = ord('a')
dfs("", 0)

Submission status: Accepted

Solution code:
N=int(input())
def f(l,m,n):
    if n==N:
        print(''.join([chr(ord('a')+i) for i in l]))
    else:
        for i in range(m+2):
            f(l+[i],max(m,i),n+1)
f([0],0,1)

Submission status: Accepted

Solution code:
import itertools

n = int(input())
alpha = "abcdefghij"
ans_s = {}
if n == 1:
    print("a")
    exit()

def ans_string(max_num, num, ans):
    if num == 0:
        ans_s[ans] = 1
    else:
        for i in range(max_num + 2):
            ans_string(max(i, max_num), num - 1, ans + alpha[i])
        
ans_string(0, n - 1, "a")
for key, value in ans_s.items():
    print(key)

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**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):
        f(s + l_alp[i], last, N)

    f(s + l_alp[last], last+1, N)


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

    f('a', 1, N)

    for a in ans:
        print(a)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
int1 = lambda x: int(x) - 1
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(500000)


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


N = int(read())
dfs("", "a")

Submission status: Accepted

Solution code:
n = int(input())
def dfs(s, i):
    if i == n:
        print(s)
    else:
        for j in range(ord("a"), max(map(ord, list(s))) + 2):
            dfs(s + chr(j), i + 1)
dfs("a", 1)

Submission status: Accepted

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, max_num):
        if i == N:
            ans.append(s)
            return

        for n in range(max_num+2):
            dfs(s + num_to_alp[n], i+1, max(max_num, n))

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


if __name__ == "__main__":
    main()

Submission status: Accepted

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(max(array) + 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: Accepted

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

def dfs(s, n):
    if len(s) == N:
        print(s)
        return
    for i in range(n+1):
        dfs(s+alp[i], max(n, i+1))

dfs("", 0)

Submission status: Accepted

Solution code:
from collections import *

def dfs(l):
    if len(l)==N:
        print(''.join(l))
        return
    
    for a in range(ord('a'), ord(max(l))+2):
        l.append(chr(a))
        dfs(l)
        l.pop()
    
N = int(input())
dfs(deque(['a']))

Submission status: Accepted

Solution code:
from collections import deque
n = int(input())
abc = 'abcdefghij'
s = ''
cnt = 0
ans = deque([s])
while True:
    a = ans.popleft()
    cnt = len(a)
    if cnt == n:
        ans.append(a)
        break
    kind = len(set(a)) + 1
    for i in range(kind):
        ans.append(a + abc[i])

for i in sorted(ans):
    print(i)

Submission status: Accepted

Solution code:
import sys
def input(): return sys.stdin.readline().strip()
def mapint(): return map(int, input().split())
sys.setrecursionlimit(10**9)

N = int(input())

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

ans = []
def dfs(idx, cnt, lis):
    if idx==N:
        ans.append(''.join(lis))
        return
    for i in range(cnt):
        dfs(idx+1, cnt, lis+[alpha[i]])
    dfs(idx+1, cnt+1, lis+[alpha[cnt]])
    return

dfs(0, 0, [])
ans.sort()
for a in ans:
    print(a)

Submission status: Accepted

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[:len(set(a)) + 1]:
            ans2 += [a + b]
    ans = ans2
print('\n'.join(ans))

Submission status: Accepted

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


def solve(N: int):
    def f(i, h):
        if i == N:
            yield ""
            return
        for c in range(ord('a'), h):
            for s in f(i+1, h):
                yield chr(c) + s
        for s in f(i+1, h+1):
            yield chr(h) + s
    return f(0, 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: Accepted

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+1,nowmax)))
        return ret

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

Submission status: Accepted

Solution code:
N = int(input())

def dfs(ans, MAX):
    if len(ans) == N:
        print(ans)
        return
    for i in range(MAX-95):
        dfs(ans + chr(97+i), max(MAX, 97+i))

dfs('a', 97)

Submission status: Accepted

Solution code:
alpha = list("abcdefghij")


def dfs(v, depth):
    if depth == N:
        print(v)
        return
    if depth <= N:
        for next_ in alpha[: len(set(list(v))) + 1]:
            dfs(v + next_, depth + 1)


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

    dfs("a", depth=1)

Submission status: Accepted

Solution code:
import sys
import itertools
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline

in_n = lambda: int(readline())
in_nn = lambda: map(int, readline().split())
in_nl = lambda: list(map(int, readline().split()))
in_na = lambda: map(int, read().split())
in_s = lambda: readline().rstrip().decode('utf-8')


def main():

    N = in_n()
    ans = []

    def dfs(s):

        if len(s) == N:
            ans.append(s)
            return

        maxs = max(map(ord, s))
        for i in range(ord('a'), maxs + 2):
            dfs(s + chr(i))

    dfs('a')
    print('\n'.join(sorted(ans)))


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
# https://atcoder.jp/contests/panasonic2020/tasks/panasonic2020_d


def main():
    n = int(input())
    data = [chr(ord("a") + i) for i in range(10)]
    generate("a", 0, n, data)


def generate(cur, max_i, n, data):
    if len(cur) == n:
        print(cur)
        return
    for i in range(max_i + 2):
        generate(cur + chr(ord("a") + i), max(max_i, i), n, data)


if __name__ == '__main__':
    main()

Submission status: Accepted

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, max(res[0:a+1])+2):
        do(a + 1, i)
do(0, 1)

Submission status: Accepted

Solution code:
n = int(input())
alp = [chr(i + 97) for i in range(26)]

ans = [[] for _ in range(n)]
ans[0] = ['a']
for i in range(1, n):
    for j in ans[i - 1]:
        for k in range(len(set(j)) + 1):
            ans[i].append(j + alp[k])
print(*ans[n - 1], sep='\n')

Submission status: Accepted

Solution code:
from collections import deque
import sys
n = int(input())
if n == 1:
    print('a')
    sys.exit()

q = deque([])
q.append((1, 'a', '1'))
cur = 1
while cur != n:
    num = len(q)
    j = 0
    while j < num:
        a, b, c = q.popleft()
        for i in range(1, max(map(int, list(c)))+2):
            q.append((i, b + chr(96+i), c + str(i)))
        j += 1
    cur += 1

for i in range(len(q)):
    a, b, c = q.popleft()
    print(b)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
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(str, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
#import numpy as np
from decimal import *
        
#再帰バージョン
N = INT()

def DFS(n):
    if len(n) == N:
        print(n)
    else:
        for i in range(len(set(n))+1):
            m = n+ascii_lowercase[i]
            DFS(m)

DFS("a")

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
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(str, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
#import numpy as np
from decimal import *
        
#非再帰バージョン
N = INT()

w = ["a"]

while  w:
    s = w.pop()
    if len(s) == N:
        print(s)
        continue
    else:
        for j in range(len(set(s)), -1, -1):
            t = s+ascii_lowercase[j]
            w.append(t)

Submission status: Accepted

Solution code:
import sys, re
from collections import deque, defaultdict, Counter
from math import ceil, sqrt, hypot, factorial, pi, sin, cos, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
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(str, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
#import numpy as np
from decimal import *
        
N = INT()

w = []

n = "a"

def DFS(n):
    if len(n) == N:
        w.append(n)
    else:
        for i in range(len(set(n))+1):
            m = n + ascii_lowercase[i]
            DFS(m)

DFS(n)
print(*w, 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, tan, asin, acos, atan, radians, degrees, log2, gcd
from itertools import accumulate, permutations, combinations, combinations_with_replacement, product, groupby
from operator import itemgetter, mul
from copy import deepcopy
from string import ascii_lowercase, ascii_uppercase, digits
from bisect import bisect, bisect_left, insort, insort_left
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(str, input().split()))
def ZIP(n): return zip(*(MAP() for _ in range(n)))
sys.setrecursionlimit(10 ** 9)
INF = float('inf')
mod = 10 ** 9 + 7
#import numpy as np
from decimal import *
        
N = INT()

w = []

n = "a"

def DFS(n):
    if len(n) == N:
        w.append(n)
        return
    else:
        for i in range(len(set(n))+1):
            m = n + ascii_lowercase[i]
            DFS(m)

DFS(n)
print(*w, sep= "\n")

Submission status: Accepted

Solution code:
n=int(input())
al=['a','b','c','d','e','f','g','h','i','j','k']
a=[['a',0]]
b=[]
for k in range(n-1):
    for i in a:
        for j in range(i[1]+2):
            b.append([i[0]+al[j],max(i[1],j)])
    a=b
    b=[]
a.sort(key=lambda x:x[0])
for i in a:
    print(i[0])

Submission status: Accepted

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, max(a) + 2):
        dfs(a + [i], size)

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

Submission status: Accepted

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(map(lambda x: chr(x + ord('a')), buf)))
            return
        for num in range(max(buf) + 2):
            create_string(digit+1, buf+[num])
    
    create_string(1, [0])
    
    

if __name__ == "__main__":
    main()

Submission status: Accepted

Solution code:
N = int(input())
string = [0 for i in range(N)]
calc_str = lambda :"".join(list(chr(i+ord('a')) for i in string))
chr_a = ord('a')
print(calc_str())
now = N-2


while N > 1:
    if string[now+1]-max(string[:now+1]) > 0:
        if now == 0: break
        string[now+1] = 0
        now -= 1
        
    else:
        string[now+1] += 1
        now = N-2

        print(calc_str())

Submission status: Accepted

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

def stds(n):
    if n == 1:
        return set(['a'])
    else:
        std = stds(n-1)
        ret = set([])
        for stdi in std:
            for x in range(ord('a'),max(map(ord,list(stdi))) + 2):
                ret.add(stdi + chr(x))
        return ret

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


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
alpha = "abcdefghij"
n = int(input())
def dfs(s,k):
    if len(s) == n:
        print(s)
    else:
        for i in range(k+1):
            if i == k:
                dfs(s+alpha[i],k+1)
            else:
                dfs(s+alpha[i],k)
dfs("",0)

Submission status: Accepted

Solution code:
n = int(input())


def dfs(n, s, idx):
    l = len(s)
    if n == l:
        print(s)
        return
    alpha = "abcdefghijklmnopqrstuvwxyz"
    i = 0
    while i < idx + 1:
        if i == idx:
            dfs(n, s + alpha[i], idx + 1)
        else:
            dfs(n, s + alpha[i], idx)
        i += 1


dfs(n, "", 0)

Submission status: Accepted

Solution code:
n=int(input())
def dfs(s):
  if len(s)==n:
    print(s)
  else:
    for i in range(ord('a'),max(map(ord,list(s)))+2):
      dfs(s+chr(i))
dfs('a')

Submission status: Accepted

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

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

Submission status: Accepted

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,top):
    if i == n:
        ans.append(s)
    else:
        for k in range(top+1):
            solve(i+1,''.join([s,chr(ord('a')+k)]), max(k+1,top))

solve(1,'a',1)

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

Submission status: Accepted

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:
        flag = False
        for j in "abcdefghij":
            if flag:
                break
            if j not in i:
                flag = True
            ret2.append(i + j)
    return dfs(cnt + 1, n, ret2)

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

Submission status: Accepted

Solution code:
n = int(input())
alpha = "abcdefghij"
lst = []
def f(s,k):
    if len(s) == n:
        print(s) 
        return
    for i in range(k+1):
        if i == k: f(s+alpha[i],k+1)
        else: f(s+alpha[i],k)
f("",0)