解决方案非常简单明了。
假设我们正在为 索引 i 执行此操作。
我们通过将子序列扩展到限制(索引)x[i] 和 i 之外来生成子序列,因为子序列将始终从 获取数组元素x[i] 到 i,如果我们只扩展,我们的子序列将始终具有索引 x[i] 和 i。
当然,我们还将涵盖从 x[i] 到 i 的明显子序列,这是第一个子序列。
编辑:为避免重复,我们必须检查给定的左右边界组合是否已经尝试过。
为此,我们将制作一个邻接列表,其中将包含
N 个链表。
所有链表最初都是空的。
现在一个给定的具有相应左右边界的子序列之前没有被尝试过当且仅当
linked list arr[left] does not contain element right.
如果链表 arr[left] 包含元素 right 则表示该子序列之前已经打印过。
首先我们将子序列的左边界固定为 x[i],然后使用新的左边界尝试所有可能的新右边界:
i,i+1,i+2 ....... N-1 , N is equal to length of array a.
Corresponding subsequenes being
if(a[j] linked list does not contain i)
{
print the subsequence a[j],a[j+1],......a[i]
add i to arr[j]
}
if(a[j] linked list does not contain i+1)
{
print the subsequence a[j],a[j+1],.........a[i+1]
add i+1 to a[j]
}
and similar if condition before all subsequences given below.
a[j],a[j+1],...............a[i+2]
.
.
a[j],a[j+1]..........................a[N-1]
j is x[i] for the above subsequences.
然后我们将左边界固定为 x[i]-1,然后使用新的左边界尝试所有可能的新右边界:
i,i+1,i+2 ....... N-1
对应的子序列是
similar if condition as given above before all subsequences given below.
and they will be printed if and only if the condition is true.
a[j],a[j+1],.........a[i]
a[j],a[j+1],...............a[i+1]
.
.
a[j],a[j+1]..........................a[N-1]
j is x[i]-1 for the above subsequences.
我们这样做直到 j 变为 0,这将是最后一次迭代。
现在来看看这个算法的效率,因为在每一步我都在生成一个新的子序列,并且没有一个步骤浪费在生成一个不包含两个索引的子序列上,所以我认为它非常有效。