209、不大于n的数的组合(python)
题目
已知一个数n和可组合的数字集合s,通过组合数字集合构成一个数x,使其不大于n。
例如:
n = 22356789
a = [2, 3, 4, 8, 9]
x = 22349999
代码实现
n = 22356789
a = [2, 3, 4, 8, 9]
a.sort()
s = str(n)
tag = True
res = []
for i in range(len(s)):
cur = int(s[i])
j = 0
# 当没有找到停顿点时
if tag:
while j < len(a) and a[j] < cur:
j += 1
# 字典中有等于的数
if a[j] == cur:
res.append(a[j])
# 字典中没有等于的数且比该数大,则为停顿点
else:
res.append(a[j - 1])
tag = False
# 已经找到停顿点,后续的都保持最大的值
else:
res.append(a[-1])
print(res)