Рекурсивная функция, вызывающая сама себя, даже если она не вызывается - PullRequest
0 голосов
/ 14 апреля 2020

Вам дан массив целых чисел длины a и целого числа k. Выведите все подпоследовательности длины k из данного массива. Здесь, после выполнения последнего, вызов предполагается остановить, но он снова вызывает функцию, даже не вызывая. Я не могу найти причину этого последнего отпечатка 2 3. Я должен решить ее, используя рекурсию и циклы.

input
3
1 2 3
2

Required output
1 2
1 3
2 3

Output received
1 2
1 3
2 3

2 3
       class main{
public static void main(String[] args) throws IOException{
 Scanner s = new Scanner(System.in);
        int array_length = s.nextInt();
        int[] n = new int[array_length];
        for(int i=0;i<array_length;i++)
        n[i] = s.nextInt();
        int sub = s.nextInt();
        solve(n,array_length,sub,1);
    }

    static void solve(int[] n, int array_length, int sub, int i){
        int s=sub; //storing subseq length so that after reducing i can use it
        System.out.print(n[0]+" ");
        sub--;

        for (int j=i;j<array_length;j++) {
            if(sub>0) {                  // printing the subsequence using for
                System.out.print(n[j]+" ");
                sub--;
            }
            else {       //if all the no. are printed of the seq,start loop again
                if(i<s){                   //s has the actual length of subseq
                    System.out.println();
                    solve(n,array_length,s,i+1);} //recall to print next sub seq
                else break;
            }
        }
        array_length=array_length-1;
        if(array_length>=s){   //creating new array containing next elements
            int[] f = new int[array_length];
            System.arraycopy(n,1,f,0,f.length);
            System.out.println();
            solve(f,array_length,s,1);
        } 
        else System.out.println();
    }
}
...