【华为机试】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)  # 输出结果
相关推荐
洛克大航海几秒前
Python 在系统 Windows 和 Ubuntu 中创建虚拟环境
windows·python·ubuntu·虚拟环境
ZEERO~3 分钟前
@dataclass的作用
开发语言·windows·python
!停9 分钟前
C语言单链表
c语言·数据结构·算法
几道之旅13 分钟前
pytdx能否下载期货数据呢?
python
vyuvyucd16 分钟前
MPPI算法实战:机器人避障与仿真
python
计算机徐师兄17 分钟前
Python基于Flask的广东旅游数据分析系统(附源码,文档说明)
python·flask·旅游数据分析·广东旅游数据分析系统·python广东数据分析系统·python广东旅游数据分析·python旅游数据分析系统
jarreyer19 分钟前
数据项目分析标准化流程
开发语言·python·机器学习
闻缺陷则喜何志丹20 分钟前
【回文 字符串】3677 统计二进制回文数字的数目|2223
c++·算法·字符串·力扣·回文
GZKPeng21 分钟前
pytorch +cuda成功安装后, torch.cuda.is_available 是False
人工智能·pytorch·python
我的xiaodoujiao23 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 39--生成 Allure测试报告
python·学习·测试工具·pytest