如果输入数组可能包含重复数字且值 K = 2
,如何解决this problem的第二部分示例:
1 2 3 4 ans-18
1 2 3 4 5 ans-46
1 1 2 2 3 ans-26
1 1 1 2 2 ans-10
1 1 2 2 3 4 ans-56
我的方法:
首先,我计算数组中的不同数字,然后使用DP计算答案(请参阅此问题的编辑)
使用这些数字,我尝试了一些排列,但答案是错误的。
我已经用Time Complexity O(n ^ 4)解决了它,是否有更有效的解决方案来解决这个问题
答案 0 :(得分:1)
注意:代码将在Python中,因为它很容易。逻辑应适用于任何语言(或多或少)。
重申这个问题:
给你一个数组A = [1,2,3,...,n]:
在A上最多k个交换后,你能得到多少个序列(S2)?可以在阵列A,A [i]和A [i + 1]或A [i]和A [i-1]的两个元素之间进行相邻交换。 否则交换可以在数组A [i]和A [j]∀1≤i之间的任何两个元素之间,j≤N,i≠j。
让我们来解决我们需要做的事情:
现在,我可以一次一个地解决每个“要求”。
D = [1,2,3,4]
,例如master_list = []
perm_count(orig_list, k)
和permuter(my_list)
A = [1,2,3,4,5]
B = [1,1,2,2,3]
C = [1,2,3]
D = [1,2,3,4]
def perm_count(orig_list, k):
master_list = []
master_list.append(list(orig_list))
while k > 0:
big_list = list(master_list) #"Snapshot" to ensure list-stability
for each_list in big_list: #Looks at all the permutations from the previous "generations"
for each_temp_list in permuter(each_list):
if each_temp_list not in master_list:
master_list.append(each_temp_list)
#our masterlist now contains all the distinct lists from this run
#If we run it again (the "k"), we get 2-swap combinations
#and so on...
k-=1
total_count = len(master_list)
print sorted(master_list) #If you need a sanity check, feel free to leave out
return total_count
#end perm_count
def permuter(my_list):#returns a list of lists
lists_list = []
#The below loop block returns all possible 1-swap combinations.
for i in range(len(my_list)):
for j in range(len(my_list)):
temp_list = my_list[:]
if i != j:
temp_list[i],temp_list[j] = temp_list[j],temp_list[i]
if temp_list not in lists_list:
lists_list.append(list(temp_list))
return lists_list
#end permuter
print perm_count(B,2)
答案 1 :(得分:0)