-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathLIS.cpp
56 lines (46 loc) · 1.25 KB
/
LIS.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
problem link: https://leetcode.com/problems/longest-increasing-subsequence/
*/
#include <iostream>
#include <vector>
using namespace std;
class RecSolution
{
public:
int f(int idx, int prev_idx, vector<int> &nums)
{
if (idx == nums.size())
return 0;
int not_take = 0 + f(idx + 1, prev_idx, nums);
int take = 0;
if (prev_idx == -1 || nums[idx] > nums[prev_idx])
take = 1 + f(idx + 1, idx, nums);
return max(take, not_take);
}
int lengthOfLIS(vector<int> &nums)
{
return f(0, -1, nums);
}
};
class MemoSolution
{
public:
int f(int idx, int prev_idx, vector<int> &nums, vector<vector<int>> &dp)
{
if (idx == nums.size())
return 0;
if (dp[idx][prev_idx + 1] != -1)
return dp[idx][prev_idx + 1];
int not_take = 0 + f(idx + 1, prev_idx, nums, dp);
int take = 0;
if (prev_idx == -1 || nums[idx] > nums[prev_idx])
take = 1 + f(idx + 1, idx, nums, dp);
return dp[idx][prev_idx + 1] = max(take, not_take);
}
int lengthOfLIS(vector<int> &nums)
{
int n = nums.size();
vector<vector<int>> dp(n, vector<int>(n + 1, -1));
return f(0, -1, nums, dp);
}
};