我希望能够在给定的字符串中找到所有可能的最长递增子序列。
例如:给定字符串是qapbso
这里最长递增子序列的长度是3。 我想要找到所有长度为3的最长子序列,即 "abs"、"aps" 和 "abo"。
我正在使用动态规划,但只得到一个 LIS。我想列出所有的 LIS。
我希望能够在给定的字符串中找到所有可能的最长递增子序列。
例如:给定字符串是qapbso
这里最长递增子序列的长度是3。 我想要找到所有长度为3的最长子序列,即 "abs"、"aps" 和 "abo"。
我正在使用动态规划,但只得到一个 LIS。我想列出所有的 LIS。
int st[1000];
int st_index
void rec(int index) {
if (dp[index] == 1) {
cout << "Another sequence:\n";
for (int i = 0; i < st_index; ++i) {
cout << st[i] << endl;
}
}
for (int j = index + 1; j < n; ++j) {
if (dp[j] == dp[index] - 1 && a[j] >= a[index]) {
st[st_index++] = a[j];
rec(j);
st_index--;
}
}
}
def lis(a): # assumes a != []
n = len(a)
dp = [1 for _ in range(n)]
# dp[k] = length of LIS with first element a[k]
max_length = 1
for k in range(n - 1, -1, -1):
result = 1
for i in range(k + 1, n):
if a[i] > a[k]:
result = max(result, 1 + dp[i])
dp[k] = result
max_length = max(max_length, result)
# printing all LISs
st = [None for _ in range(max_length)]
st_index = 0
def rec(index): # credit: Ivaylo Strandjev
nonlocal st_index, dp, a
if dp[index] == 1:
print("Another sequence:")
for i in range(st_index):
print(st[i])
for j in range(index + 1, n):
if dp[j] == dp[index] - 1 and a[j] >= a[index]:
st[st_index] = a[j]
st_index += 1
rec(j)
st_index -= 1
# beginning the recursion at each valid index
for index in range(n):
if dp[index] == max_length:
st_index = 1
st[0] = a[index]
rec(index)
return max_length
store
,并且在打印逻辑的位置写入store.append(st.copy())
。store
,并且在逻辑的位置写入store.add(tuple(st))
。