How can I properly return ArrayList<Object> from recursive method without repeated values?

家住魔仙堡 提交于 2019-12-24 11:43:14

问题


I need a recursive solution which returns any combination of n subset from k set (in mathematical sense). I have an ArrayList and I want return any possible n-size subsets from recursive method. Order doesn't matter. So if I have set of employees {Jim, Tom, Ann, John} and want 2 of them I should get:

{Jim Tom}{Jim Ann}{Jim John}{Tom Ann}{Tom John}{Ann John}

I found this https://stackoverflow.com/a/16256122/10929764 but it only prints out result. I modified it a bit to add any combination to ArrayList and return it, but it doesn't work properly. Here is a code:

    public ArrayList<Employee[]> combinationsOfEmployee(ArrayList<Employee>sourceList, int selected, int startIndex, Employee[] result, ArrayList<Employee[]>allResults){
        if(selected == 0){
            for(int i=0; i<result.length; i++){
                System.out.print(result[i].getLastName() + "  ");
            }
            System.out.println("");
            allResults.add(result);
            return allResults;
        }
        for(int i=startIndex; i<=sourceList.size() - selected; i++){
            result[result.length - selected] = sourceList.get(i);
            combinationsOfEmployee(sourceList, selected - 1, i + 1, result, allResults);
        }
        return allResults;
    }

It prints out properly all combinations, but adds the same values all the time to ArrayList. So allResults is

{Ann, John}{Ann, John}{Ann, John}{Ann, John}{Ann, John}{Ann, John}

instead of:

{Jim Tom}{Jim Ann}{Jim John}{Tom Ann}{Tom John}{Ann John}


回答1:


You are wondering why it prints it fine while the returned list seems to have the exact same array at each position.
That's because it's the exact same array (same reference to the same object). Since in your solution you are using only one array, when you call allResults.add(result), you add the reference to your only array in the list. Then you keep modifying it when you look for the other combinations. That's why your list only contains the last combination found.

The solution to this is to add a new array each time you find a combination by adding a copy of your current array to your list. Simply replace

allResults.add(result);

by

allResults.add(Arrays.copyOf(result, result.length));

That way, every element of your list points to a different array.



来源:https://stackoverflow.com/questions/54250376/how-can-i-properly-return-arraylistobject-from-recursive-method-without-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!