【Java求助】90分第二个测试点RE,本地IDE调试报递归堆栈溢出了
查看原帖
【Java求助】90分第二个测试点RE,本地IDE调试报递归堆栈溢出了
811090
lsiuf楼主2022/12/5 19:07

参考CPP题解,代码如下

import java.util.*;
import java.io.*;

public class Main{

    static StreamTokenizer st;
    static PrintWriter pw;

    static int nextInt() throws IOException{
        st.nextToken();
        return (int) st.nval;
    }

    static int n,m,count;
    static boolean flag;
    static int[] nums = new int[10010];
    static boolean[] judges = new boolean[10010];

    static void dfs(int step){
        if(flag){
            return;
        }
        if(step == n){
            count++;
            if(count == (m+1)){
                for(int i=0; i<n; i++){
                    pw.format("%d ",nums[i]);
                }
                pw.println();
                flag = true;
            }
            return;
        }
        for(int i=0; i<n; i++){
            if(count == 0){
                i = nums[step] - 1;
            }
            if(!judges[i]){
                judges[i] = true;
                nums[step] = i + 1;
                dfs(step+1);
                judges[i] = false;
            }
        }
    }

    public static void main(String[] args) throws IOException{
        st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        n = nextInt();
        m = nextInt();
        for(int i=0; i<n; i++){
            nums[i] = nextInt();
        }
        dfs(0);
        pw.close();
    }
}

 

本地IDE异常信息如下

Exception in thread "main" java.lang.StackOverflowError
 at com.luoguoi.Main.dfs(Main.java:47)
 at com.luoguoi.Main.dfs(Main.java:47)
 at com.luoguoi.Main.dfs(Main.java:47)
 at com.luoguoi.Main.dfs(Main.java:47)
 at com.luoguoi.Main.dfs(Main.java:47)
 at com.luoguoi.Main.dfs(Main.java:47)
 at com.luoguoi.Main.dfs(Main.java:47)
   ......
2022/12/5 19:07
加载中...