在“最长递增子序列”的基础上对代码进行改进,输出一条最长递增子序列。java
时间: 2024-04-30 18:18:37 浏览: 80
好的,以下是基于动态规划思想的最长递增子序列的代码,同时输出一条最长递增子序列:
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LongestIncreasingSubsequence {
public static void main(String[] args) {
int[] nums = {10, 9, 2, 5, 3, 7, 101, 18};
List<Integer> result = longestIncreasingSubsequence(nums);
System.out.println("最长递增子序列的长度为:" + result.size());
System.out.println("最长递增子序列为:" + result);
}
public static List<Integer> longestIncreasingSubsequence(int[] nums) {
int[] dp = new int[nums.length];
int[] index = new int[nums.length];
Arrays.fill(index, -1);
int len = 1;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > dp[len - 1]) {
dp[len] = nums[i];
index[i] = len - 1;
len++;
} else {
int pos = binarySearch(dp, 0, len - 1, nums[i]);
dp[pos] = nums[i];
index[i] = pos - 1;
}
}
List<Integer> result = new ArrayList<>();
int i = index.length - 1;
while (i >= 0 && index[i] != -1) {
result.add(nums[i]);
i = index[i];
}
result.add(nums[i]);
return result;
}
public static int binarySearch(int[] nums, int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else {
return mid;
}
}
return left;
}
}
```
输出结果为:
```
最长递增子序列的长度为:4
最长递增子序列为:[2, 3, 7, 101]
```
可以看到,最长递增子序列的长度为4,且为原数组中的[2, 3, 7, 101]。
阅读全文