DFS组合解法 会超时
import java.util.*;
public class Mian{
static int a[]=new int[1005];
static int n;
static HashSet<Integer> set=new HashSet<>();
static boolean v[]=new boolean[1005];//标记是否已经访问
static int b[]=new int[5];//保存记录三元组数
static int bb[]=new int[5];//保存记录三元组元素在a数组中的下标
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
//输入样例
for(int i=1;i<=n;i++){
a[i]=sc.nextInt();
}
dfs(1);
System.out.println(set.size());
}
public static void dfs(int x){
if(x>3){
boolean flag=false;
if(b[2]>b[1]&&b[2]<b[3]){
set.add(bb[2]);//set必须保存下表,因为题目中要求的是多少元素,而不是元素大小,如果保存大小可能去重会把正确的去除
}
return;
}
for(int i=1;i<=n;i++){
if(!v[i]&&i>bb[x-1]){
v[i]=true;
b[x]=a[i];
bb[x]=i;
dfs(x+1);
bb[x]=0;
b[x]=0;
v[i]=false;
}
}
}
}
Java题解2:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] a = new int[n];
int[] vis = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scan.nextInt();
}
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
if (a[j] > a[i] && a[j] < a[k]) {
vis[j] = 1;//记录中心元组下标
}
}
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (vis[i] == 1)
ans++;
}
System.out.println(ans);
}
}