动态规划求最长上升子序列

来源:互联网 发布:premiere cs6 mac下载 编辑:程序博客网 时间:2024/04/30 07:49

realoj 134

1,7,3,5,9,4,8的子序列为(1,7)(3,4,8)等,最长子序列为(1,3,5,8);

状态转移方程:

maxLen(1)  = 1;

maxLen(k)  = max{maxLen(i):1<=i<k且ai<ak且k!=1}+1;

即,maxLen的值,就是在ak的左边,终点数值小于ak,且长度最大的那个上升子序列的长度再加1.因为任何终点数小于ak的子序列,加上ak后就能形成一个更长的上升子序列。

 

java实现:

import java.util.ArrayList;import java.util.List;class element {int index = 0;int ele = 0;int length = 0;}public class zuichangzixulie {public static void main(String[] args) {int[] nums = { 1, 7, 3, 5, 9, 4, 8 };System.out.println(getans(nums));}private static int getans(int[] nums) {List<element> ls = new ArrayList<element>();for (int i = 0; i < nums.length; i++) {element e = new element();e.index = i;e.ele = nums[i];ls.add(e);if (i == 0) {e.length = 1;continue;}for (int j = i; j >= 0; j--) {element temp = ls.get(j);if (temp.ele < e.ele) {if (temp.length > e.length) {e.length = temp.length + 1;}}}}int maxLength = 0;for (int i = 0; i < ls.size(); i++) {if (ls.get(i).length > maxLength) {maxLength = ls.get(i).length;}}return maxLength;}}


 

 

 

原创粉丝点击