【发布时间】:2018-04-03 15:05:42
【问题描述】:
我刚从一本书中看到这个有趣的问题,但我找不到答案。
我有一个给定的数字 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 ]) 是最小值。但这在很多情况下都失败了。
我正在尝试一种 DP 方法,但无法提出任何方法。
任何导致答案的线索都会有所帮助。
编辑 - 为我的贪婪方法添加伪代码
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.
【问题讨论】:
-
你能提供你贪婪方法的伪代码吗?在这种情况下它会失败吗?因为你的贪婪对我来说似乎是正确的。
-
@PhamTrung 我已经编辑了这个问题。看看吧。
-
这个问题有什么限制吗?
-
没有。这也是我想知道的。我正在尝试获得任何多项式时间解决方案。
标签: algorithm permutation