暴力搜索解法(会超时)
//最简单最直接的暴力搜索思想 会超时
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int max2 = 1;
for (int i = 0; i < nums.size(); i++)
{
max2 = max(max2, Max(nums, i));
}
return max2;
}
int Max(vector<int>& nums, int m)
{
int max1 = 1;
if (m == nums.size() - 1)
return 1;
for (int j = m + 1; j < nums.size(); j++)
{
if (nums[j] > nums[m])
{
max1 = max(max1, Max(nums, j) + 1);
}
}
return max1;
}
};
剪枝Pruning 以空间换时间
//Pruning剪枝改进一下 增加一个数组记录避免重复节点的计算 记忆化搜索 以空间换时间
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int max2 = 1;
for (int i = 0; i < nums.size(); i++)
{
max2 = max(max2, Max(nums, i));
}
return max2;
}
int num[2500] = { 0 };
int Max(vector<int>& nums, int m)
{
if (num[m] != 0)
return num[m];
int max1 = 1;
if (m == nums.size() - 1)
return 1;
for (int j = m + 1; j < nums.size(); j++)
{
if (nums[j] > nums[m])
{
max1 = max(max1, Max(nums, j) + 1);
}
}
num[m] = max1;
return max1;
}
};
动态规划方法
//动态规划dp解法
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int max1 = 1;
Max_length(nums);
for (int i = 0; i < nums.size(); i++)
{
//cout<<dp[i]<<endl;
max1 = max(max1, dp[i]);
}
return max1;
}
int dp[2500] = { 0 };//首先进行dp数组的初始化
void Max_length(vector<int>& nums)
{ for(int i = 0; i < 2500; i++) dp[i] = 1;
for (int i = nums.size() - 1; i >= 0; i--)
{
for (int j = i; j < nums.size(); j++)
{
if (nums[j] > nums[i])
{
dp[i] = max(dp[i], dp[j] + 1);
}
}
}
}
};