数组的k-后继的java-返回arraylist

093gszye  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(303)

我有以下代码 prints 全部 k-subsequent 的数组 size n ```
import java.util.*;

public class Main {
public static void main(String[] args){
int[] arr = {1,2,3,4,5,6};
int k = 3;
int start= 0;
List<int[]> subs = subseq(arr, k, 0, new int[k]);

    for(int[] s : subs)
        System.out.println(Arrays.toString(s));
}

static List<int[]> subseq(int[] arr, int len, int start, int[] result){
    List<int[]> rez = new ArrayList<>();
    if (len == 0){
         /* PRINT HERE WORKS FINE IT PRINT EACH SUBSEQUENT CORRECTLY*/
        //System.out.println(Arrays.toString(result));
        rez.add(result);
        return rez;
    }       
    for (int i = start; i <= arr.length-len; i++){
        result[result.length - len] = arr[i];
        subseq(arr, len-1, i+1, result);
    }
    return rez;
}       

}

我的问题是 `rez List` 就是这样 `returned` 在 `recursive` 功能,它总是 `empty` ,有人能帮忙修理吗?我尝试了很多解决方案,但都没有成功
vxqlmq5t

vxqlmq5t1#

基本上,你要创建一个新的arraylist来存储所有的序列,你需要创建一个结果arraylist来存储所有的数组。在添加到res时,我创建了新的数组,这样就不会替换以前添加的数组。下面是工作方案

import java.util.*;

public class Main {
    public static void main(String[] args){
        int[] arr = {1,2,3,4,5,6};
        int k = 3;
        int start= 0;
        Main obj = new Main();
        List<int[]> rez = new ArrayList<>();
        obj.subseq(arr, k, start, new int[k], rez);

        for(int[] s : rez)
         System.out.println(Arrays.toString(s));
    }

    public void subseq(int[] arr, int len, int start, 
int[] result, List<int[]> 
 res){
        if (len == 0){
             /* PRINT HERE WORKS FINE IT PRINT EACH SUBSEQUENT CORRECTLY*/
         // System.out.println(Arrays.toString(result));
          int[] a = new int[result.length];
            for(int i = 0; i < result.length; i++) {
                a[i] = result[i];
          }

            res.add(a);

            return;
        }       
        for (int i = start; i <=arr.length-len; i++){
            result[result.length - len] = arr[i];
            subseq(arr, len-1, i+1, result,res);
        }         
    }       
}

相关问题