使用java语言写出最大递增子序列,并输出这个序列
时间: 2024-02-03 15:02:23 浏览: 78
好的,我来帮你写出Java代码:
```java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MaxIncreasingSubsequence {
public static void main(String[] args) {
int[] nums = {1, 3, 2, 4, 6, 5, 7};
List<Integer> result = maxIncreasingSubsequence(nums);
System.out.println("Max increasing subsequence: " + result);
}
private static List<Integer> maxIncreasingSubsequence(int[] nums) {
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int maxLen = 1;
int maxIndex = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
if (dp[i] > maxLen) {
maxLen = dp[i];
maxIndex = i;
}
}
List<Integer> result = new ArrayList<>();
result.add(nums[maxIndex]);
for (int i = maxIndex - 1; i >= 0; i--) {
if (nums[i] < nums[maxIndex] && dp[i] == dp[maxIndex] - 1) {
result.add(nums[i]);
maxIndex = i;
}
}
Collections.reverse(result);
return result;
}
}
```
这个程序使用动态规划算法,时间复杂度为O(n^2),空间复杂度为O(n)。它输出最大递增子序列,并且可以处理多个最长递增子序列的情况。
阅读全文