求最长不增子序列、最长单调递减子序列、最长不降子序列、最长单调递增子序列长度

免费午餐问题的引申:

代码如下:

#include <iostream>
#include <vector>
using namespace std;

int total = 0;
vector<int> v1;//原始数据集合
vector<int> v2;//最长不增子序列暂时集合
vector<int> v3;//最长单调递减子序列暂时集合
vector<int> v4;//最长不降子序列暂时集合
vector<int> v5;//最长单调递增子序列暂时集合

//二分法求最长不增子序列关键字下标(>=)
int binarySearch1(int key,int lowIndex,int highIndex)
{
    if(lowIndex==highIndex)
    {
        if(lowIndex == 0 && key>v2[0])
        {
            return lowIndex;
        }
        return lowIndex+1;

    }
    int midIndex = (lowIndex + highIndex + 1)/2;
    if(key<=v2[midIndex])
    {
        return binarySearch1(key,midIndex,highIndex);
    }
    else
    {
        return binarySearch1(key,lowIndex,midIndex-1);
    }
}
//二分法求最长单调递减子序列关键字下标(>)
int binarySearch2(int key,int lowIndex,int highIndex)
{
    if(lowIndex==highIndex)
  
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于一棵二叉树,我们可以定义其最长上升子序列(LIS)为从根节点开始,沿着任意路径向下遍历,使得经过的结点值单调递增最长路径长度。 为了解二叉树的 LIS,可以考虑使用动态规划(DP)的方法。具体来说,我们可以定义一个数组 dp,其中 dp[i] 表示以第 i 个结点为结尾的 LIS 长度。对于一个结点 i,其 LIS 长度可以通过枚举其所有子结点 j,如果 val[i] < val[j],则有转移方程: dp[i] = max(dp[i], dp[j] + 1) 最终的 LIS 长度即为 dp 数组中的最大值。 下面是一个 Python 代码实现: ```python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def longest_increasing_path(root: TreeNode) -> int: def dfs(node: TreeNode) -> Tuple[int, int]: if not node: return 0, 0 left_len, left_inc = dfs(node.left) right_len, right_inc = dfs(node.right) cur_len = 1 if node.left and node.left.val > node.val: cur_len = max(cur_len, left_inc + 1) if node.right and node.right.val > node.val: cur_len = max(cur_len, right_inc + 1) cur_inc = 1 if node.left and node.left.val < node.val: cur_inc = max(cur_inc, left_len + 1) if node.right and node.right.val < node.val: cur_inc = max(cur_inc, right_len + 1) return cur_len, cur_inc return dfs(root)[0] ``` 其中 dfs 函数返回一个元组,第一个元素表示以当前结点为结尾的 LIS 长度,第二个元素表示以当前结点为结尾的 LIS 递减子序列长度。对于每个结点,我们分别计算其向左子树和右子树的 LIS 长度递减子序列长度,并根据当前结点与子结点之间的大小关系来更新当前结点的 LIS 长度递减子序列长度。最终返回根节点的 LIS 长度即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值