【华为机试】2023年真题B卷(python)-考古问题

一、题目

题目描述:

考古问题,假设以前的石碑被打碎成了很多块,每块上面都有一个或若干个字符,请你写个程序来把之前石碑上文字可能的组合全部写出来,按升序进行排列。

二、输入输出

三、示例

示例1:

输入输出示例仅供调试,后台判题数据一般不包含示例

输入:

3

a b c

输出

abc

acb

bac

bca

cab

cba
示例2:

输入输出示例仅供调试,后台判题数据一般不包含示例

输入

3

a b a

输出

aab

aba

baa

四、要求

时间限制:C/C++ 1秒,其他语言 2秒

空间限制:C/C++262144K,其他语言524288K

64bit IO Format:%lld

五、解题思路

排列组合问题,简单的 DFS

六、参考代码

python 复制代码
# -*- coding: utf-8 -*-
'''
@File    :   2023-B-考古问题.py
@Time    :   2023/12/30 22:51:00
@Author  :   mgc 
@Version :   1.0
@Desc    :   None
'''

# import os
# import re
# import sys
# import copy
# import math
# import queue
# import functools
# from queue import Queue
# from collections import Counter, defaultdict

def permutations(prefix, remaining, result):
    """
    生成所有可能的排列组合

    Args:
        prefix (str): 当前生成的排列组合的前缀
        remaining (list): 剩余的字符列表
        result (list): 存储生成的排列组合的结果列表
    """
    for i in range(len(remaining)):
        str_i = prefix + remaining[i]
        remaining_i = remaining[:i] + remaining[i+1:]
        if not remaining_i:
            if str_i not in result:
                result.append(str_i)
        else:
            permutations(str_i, remaining_i, result)


result = []
num = int(input())  # 输入字符块数量
list_n = input().split(' ')  # 输入字符块列表
permutations('', list_n, result)  # 生成排列组合
result.sort()  # 对结果进行排序
for s in result:
    print(s)  # 输出结果
相关推荐
吴佳浩6 分钟前
Python入门指南-AI模型相似性检测方法:技术原理与实现
人工智能·python·llm
叶 落16 分钟前
计算阶梯电费
python·python 基础·python 入门
无聊的小坏坏30 分钟前
三种方法详解最长回文子串问题
c++·算法·回文串
长路 ㅤ   42 分钟前
Java后端技术博客汇总文档
分布式·算法·技术分享·编程学习·java后端
秋说1 小时前
【PTA数据结构 | C语言版】两枚硬币
c语言·数据结构·算法
Python大数据分析@1 小时前
Origin、MATLAB、Python 用于科研作图,哪个最好?
开发语言·python·matlab
qq_513970441 小时前
力扣 hot100 Day37
算法·leetcode
编程零零七1 小时前
Python巩固训练——第一天练习题
开发语言·python·python基础·python学习·python练习题
不見星空1 小时前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack2 小时前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法