week13-leetcode #300-Longest-Increasing-Subsequence

week13-leetcode #300-Longest-Increasing-Subsequence

链接:https://leetcode.com/problems/longest-increasing-subsequence/description/

Question

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example

Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Note:

  • Your algorithm should run in O(n2) complexity.

Solution

time complecity: O(n2)

class Solution {
public:
  int lengthOfLIS(vector<int>& nums) {
    if (nums.size() == 0) return 0;
    int num_size = nums.size();
    bool **is_relate = new bool*[num_size];
    for (int i = 0; i < num_size; i++)
      is_relate[i] = new bool[num_size];
    for (int i = 0; i < num_size; i++) {
      for (int j = 0; j < num_size; j++) {
        if (i != j && nums[i] < nums[j])
          is_relate[i][j] = true;
        else
          is_relate[i][j] = false;
      }
    }

    vector<int> L(num_size, 1);
    int result = -9999;


    for (int j = 0; j < num_size; j++) {
      int max_value = -9999;
      for (int i = 0; i < j; i++) {
        if (is_relate[i][j]) {
          max_value = max(max_value, L[i]);
        }
      }
      if (max_value > 0)
        L[j] = 1+max_value;
      result = max(result, L[j]);
    }
    return result;
  }
};

思路:将所有数据点看成是一个图中的节点,遍历所有数据,若出现 nums(i)<nums(j) 的情况,则认为存在一条从i节点到j节点的边,则问题转化为求这个有向无环图(dag)的边值权重为1的最长路径。最长路径采用动态规划的方法进行求解。其中动态规划的状态转换方程如下:
1<=j<size,L[j]=max1<=i<j{L[i]}+1,ij

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值