算法思路
- 统计原数字中每个数字出现的次数
- 从第1位到第10位依次确定数字:
- 该位置的最小允许值 = 10 - 位置索引
- 从最小允许值到9,选择可用的最小数字
- 使用后减少该数字的计数
Python代码
def find_smallest_elegant_number(number_str):
# 统计每个数字出现的次数
count = [0] * 10
for digit in number_str:
count[int(digit)] += 1
result = []
# 从第一位到第十位依次确定数字
for position in range(1, 11):
min_allowed = 10 - position # 该位置允许的最小数字
# 从最小允许值到9,找到第一个可用的数字
for digit in range(min_allowed, 10):
if count[digit] > 0:
# 检查使用这个数字后,剩余数字是否能满足后续位置的要求
temp_count = count.copy()
temp_count[digit] -= 1
# 检查后续位置是否能满足要求
can_satisfy = True
for next_pos in range(position + 1, 11):
next_min = 10 - next_pos
found = False
for d in range(next_min, 10):
if temp_count[d] > 0:
found = True
temp_count[d] -= 1
break
if not found:
can_satisfy = False
break
if can_satisfy:
result.append(str(digit))
count[digit] -= 1
break
return ''.join(result)