我刚在一本书中看到了这个有趣的问题,但是我找不到答案。
我有一个给定的数字X和一个目标数字Y,任务是找到X的所有数字的排列中最接近Y的那个。 数字以数组形式给出。没有给出数组大小限制。
示例
Given number X = 1212
Target number Y = 1500
Answer = 1221
Here, abs(1500-1221) is smallest among all permutations of X.
Given number X = 1212
Target number Y = 1900
Answer = 2112
Here, abs(1900-2112) is smallest among all permutations of X.
Given number X = 1029
Target number Y = 2000
Answer = 2019
Here, abs(2000-2019) is smallest among all permutations of X.
我找到的一种解决方法是对给定的数字生成所有排列,并在每个阶段计算差异。但是这非常慢。
我尝试寻找贪心算法,我将遍历目标数字 Y 的所有索引,并在每个索引处将给定数字 X 的那个数字放置在使 abs(Y[i] - X[i]) 最小的位置上。但是这在许多情况下失败了。
我正尝试想出一个动态规划的方法,但无法想出任何方法。
任何有关答案的线索都将有所帮助。
编辑 - 添加我的贪心方法的伪代码
for each index i in [0,Y]:
min_index = 0;
for each index j in [1, X.length]:
if abs(X[j] - Y[i]) < abs(X[min_index] - Y[i]):
min_val = j
print X[min_index]
remove min_index from X
Example X = 1212 and Y = 1900.
step 1 - output 1 and remove index 0 from X.
step 2 - output 2 and remove index 1 from X.
step 3 - output 1 and remove index 2 from X.
step 2 - output 1 and remove index 3 from X.
answer = 1212 which is wrong (correct answer is 2112).
So fails for this test case and lots more.