最长单调递增子序列问题
题目:设计一个 O( n ^ 2 )复杂度的算法,找出由 n 个数组成的序列的最长单调递增子序列。
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { int n = scanner.nextInt(); int[] nums = new int[n + 1];// 数列数据 int[] sub_len = new int[n + 1];// sub_len[i]表示从i到n的最长递增序列的长度 int[] sub_index = new int[n + 1];// sub_index[i]表示第i个数据的后面一个数据的下标 for (int i = 1; i <= n; i++) { nums[i] = scanner.nextInt(); sub_len[i] = 1; sub_index[i] = 0; } for (int i = n - 1; i >= 1; i--) { int max = 0, p = 0;// 临时变量 for (int j = i + 1; j <= n; j++) { if (nums[i] < nums[j] && sub_len[j] > max) { max = sub_len[j]; p = j; } if (p != 0) { sub_len[i] = sub_len[p] + 1; sub_index[i] = p; } } } int max = 0, p = 0; for (int i = 1; i <= n; i++) { if (sub_len[i] > max) { max = sub_len[i]; p = i; } } System.out.println("最长长度:" + max); System.out.print("最长递增序列:"); while (p != 0) { System.out.print(nums[p] + " "); p = sub_index[p]; } System.out.println(); } scanner.close(); } }
原文地址:http://blog.csdn.net/u011506951/article/details/37074901