从数字列表中形成嵌套对的算法

时间:2016-12-02 04:05:30

标签: algorithm dynamic-programming

例如,给出一个数字列表

示例输出: 0的 12 0 3 8 第3 **** 2 9 1 9 即。 1,1 2,2 3,3 max。数字是3

如何使用算法形成嵌套巴黎的最大数量?

2 个答案:

答案 0 :(得分:0)

类似于Longest Palindromic Subsequence,我猜。 O(n * n)解决方案就在那里。那是你想要的吗? 确切的程序是=> 可以使用如下的递归关系来解决该问题,
T(i,j)=>子数组[i,j]中最长嵌套对的长度是多少 现在你的答案是t(0,n-1)假设数组有N个元素,索引从0到n-1。
T(i,j)=>
如果(i> = j)T(i,j)= 0
如果(arr [i] == arr [j])T(i,j)= 2 + T(i + 1,j-1)
否则T(i,j)= max(T(i + 1,j),T(i,j-1))

现在您可以编写递归或自下而上的DP来解决重复问题。请注意,在解决重现时,您还必须跟踪哪个Segment给出了最大答案,然后您只需要遍历该段并收集所有匹配对。

答案 1 :(得分:0)

Here is a working algorithm I wrote in R. While this works it's overly verbose because I'm tired.

I can come back tomorrow and make it shorter if you need, but hopefully you can just see the logic and then make your own version in whatever language.

# Example data
num_list <- c(0,1,2,0,3,8,3,2,9,1,9)

# Declare empty vector for later
tmp <- numeric()

# Find out which numbers can be ruled out based on frequency
cnt <- as.data.frame(table(num_list))

# Keep pairs, fix data classes
for(i in unique(cnt$num_list)){
  if(cnt$Freq[cnt$num_list==i] == 2){
    tmp <- c(as.numeric(as.character(
      cnt$num_list[cnt$num_list == i])), tmp)    
  }  
}

num_list <- num_list[num_list%in%tmp]

# Figure out where the max (peak) number is, to cut the data 
peak <- numeric()
for(i in 1:(length(num_list)-1)){
  if(!is.na(num_list[i]) & num_list[i] == num_list[i+1]){
    peak <- num_list[i]
  }
}

# Apply nesting filter to first half of data
drop <- numeric()
for(i in 1:(length(num_list)-1)){
  if(!is.na(num_list[i]) & num_list[i] == peak){
    break
  } else if(!is.na(num_list[i]) & num_list[i] > num_list[i+1]){
    num_list[i+1] <- NA
  }
}

num_list <- num_list[!is.na(num_list)] 
num_list <- num_list[!num_list %in% 
                     unique(num_list)[table(num_list)==1]]

num_list.beg <- num_list[1:(max(which(num_list==peak)))]
num_list.end <- num_list[(max(which(num_list==peak))+1):length(num_list)]

# Apply nesting filter to second half of data     
for(i in 1:(length(num_list.end)-1)){
 if(!is.na(num_list.end[i]) & num_list.end[i] <= num_list.end[i+1]){
   num_list.end[i+1] <- NA
  }
}

num_list.end <- num_list.end[!is.na(num_list.end)]
num_list     <- c(num_list.beg, num_list.end)

# Sort them like you did in your desired output
sort(num_list)

1 1 2 2 3 3