求一个int数组的元素相加为某值的所有组合,获得组合中元素的下标

注:
元素个数为任意的,可能两个相加,三个相加,n个相加......

这个数组中含有重复元素,元素值相同但是下标不同视为不同的组合.

@org.junit.Test
    public void forScore(){
        int[] es = {1,2,4,5,4,6,2,3,5};
        int result = 8;

        List<List<Integer>> list = count(es, 0, -1, result);
        System.out.println(list);

        for(List<Integer> l:list){
            for(Integer i:l){
                System.out.print(es[i]+",");
            }
            System.out.println();
        }
    }

    public List<List<Integer>> count(int[] es, int sum, int currIndex, int result){
        List<List<Integer>> indexLink = new ArrayList<>();
        for(int i=currIndex+1; i<es.length; i++){
            int s = es[i]+sum;
            if(s < result){
                List<List<Integer>> iLink = count(es, s, i, result);

                for(List list:iLink){
                    list.add(0,i);
                }

                if(iLink.size() > 0){
                    indexLink.addAll(iLink);
                }

            }else if(s > result){
                continue;
            }else{
                List<Integer> list = new ArrayList<>();
                list.add(i);
                indexLink.add(list);
            }
        }

        return indexLink;
    }

打印:

[[0, 1, 3], [0, 1, 6, 7], [0, 1, 8], [0, 2, 7], [0, 3, 6], [0, 4, 7], [0, 6, 8], [1, 2, 6], [1, 4, 6], [1, 5], [2, 4], [3, 7], [5, 6], [7, 8]]
1,2,5,
1,2,2,3,
1,2,5,
1,4,3,
1,5,2,
1,4,3,
1,2,5,
2,4,2,
2,4,2,
2,6,
4,4,
5,3,
6,2,
3,5,