LeetCode Longest Increasing Subsequence
2015-11-17 21:17
435 查看
题目:
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given
The longest increasing subsequence is
Note that there may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
给定一个数组,然后计算数组中的最长递增子序列的长度,要求在O(n^2)的时间复杂度内完成。首先一开始这题我不是很理解,以为是这个最长递增子序列,是要求每一段中都是连续递增的,其实它是可以断断续续的,也就是说其实它是可以中间断的,不一定要连续,那么考虑采用动态规划来做,其实这也是一道非常典型的动态规划的题目,考虑当前的状态和状态转移方程。首先我们看到当循环到当前这个数组下标的值时,考虑与之前的每一个数组下标中的元素的值的大小比较情况,其实也就是d(i)
= max{1,d(j) + 1},其中j < i,A[j] <= A[i],就是在内层循环中得每一个都得和当前的比,如果是比当前的那个值大的,那么当前位置对应的那个d(j)值就加1,然后赋给d(i),每次在内层循环完之后,就判断和最大的那个比较,如果比最大的那个还大,那么就赋值,否则就不用赋值。
public class Solution
{
public int lengthOfLIS(int[] nums)
{
int length = nums.length;
if(length == 0)
return 0;
int len = 1;
int[] lis = new int[length + 1];
for(int i = 0; i < length; i++)
{
lis[i] = 1;
for(int j = 0; j < i; j++)
{
if(nums[j] < nums[i] && lis[j] + 1 > lis[i])
lis[i] = lis[j] + 1;
}
if(lis[i] > len)
len = lis[i];
}
return len;
}
}
Given an unsorted array of integers, find the length of longest increasing subsequence.
For 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.
Your algorithm should run in O(n2) complexity.
给定一个数组,然后计算数组中的最长递增子序列的长度,要求在O(n^2)的时间复杂度内完成。首先一开始这题我不是很理解,以为是这个最长递增子序列,是要求每一段中都是连续递增的,其实它是可以断断续续的,也就是说其实它是可以中间断的,不一定要连续,那么考虑采用动态规划来做,其实这也是一道非常典型的动态规划的题目,考虑当前的状态和状态转移方程。首先我们看到当循环到当前这个数组下标的值时,考虑与之前的每一个数组下标中的元素的值的大小比较情况,其实也就是d(i)
= max{1,d(j) + 1},其中j < i,A[j] <= A[i],就是在内层循环中得每一个都得和当前的比,如果是比当前的那个值大的,那么当前位置对应的那个d(j)值就加1,然后赋给d(i),每次在内层循环完之后,就判断和最大的那个比较,如果比最大的那个还大,那么就赋值,否则就不用赋值。
public class Solution
{
public int lengthOfLIS(int[] nums)
{
int length = nums.length;
if(length == 0)
return 0;
int len = 1;
int[] lis = new int[length + 1];
for(int i = 0; i < length; i++)
{
lis[i] = 1;
for(int j = 0; j < i; j++)
{
if(nums[j] < nums[i] && lis[j] + 1 > lis[i])
lis[i] = lis[j] + 1;
}
if(lis[i] > len)
len = lis[i];
}
return len;
}
}
相关文章推荐
- UI基础-UIControl及其子类
- 18.UIStepper
- 随意细解:UI -- UISegmentedControl、UISlider
- UEFI的helloworld程序
- LeetCode OJ:Longest Increasing Subsequence(最长递增序列)
- Machine Learning week 3 quiz : Regularization
- UVA 11995 - I Can Guess the Data Structure!【stl】
- 在uistoryboard中实现scrollView的添加内容的操作注意事项
- poj 2593Max Sequence【dp】
- mac os slave Slave went offline during the build issue
- My 1st webUI try
- UISegmentedControl 分段控制 一个小demo
- 《iOS Human Interface Guidelines》——Integrating with iOS
- UI 第六天 UISegmentControl UISlider UIImageView
- Frequently Asked Questions in Spark
- UI note1
- UITableView - beginUpdates和endUpdates
- AMD规范与requireJS
- [TwistedFate]滑块UISlider 跑图UIImageView
- UIControl的两个子类 -- UISegmentedControl UISlider