Java - Permutation of ArrayList elements (Integer) - Can't get it to work properly

后端 未结 2 631
说谎
说谎 2020-12-19 19:05

I\'ve been looking around quite a bit to solve my issue. I got many problems solved but this one is still haunting me :S It\'s been a long time I haven\'t touch Java program

2条回答
  •  情歌与酒
    2020-12-19 19:43

    Try this, it seems to work, it uses recursion.

    public class Permute {
    
        public static List> permute(Integer...myInts){
    
            if(myInts.length==1){
                List arrayList = new ArrayList();
                arrayList.add(myInts[0]);
                List > listOfList = new ArrayList>();
                listOfList.add(arrayList);
                return listOfList;
            }
    
            Set setOf = new HashSet(Arrays.asList(myInts));   
    
            List> listOfLists = new ArrayList>();
    
            for(Integer i: myInts){
                ArrayList arrayList = new ArrayList();
                arrayList.add(i);
    
                Set setOfCopied = new HashSet();
                setOfCopied.addAll(setOf);
                setOfCopied.remove(i);
    
                Integer[] isttt = new Integer[setOfCopied.size()];
                setOfCopied.toArray(isttt);
    
                List> permute = permute(isttt);
                Iterator> iterator = permute.iterator();
                while (iterator.hasNext()) {
                    List list = iterator.next();
                    list.add(i);
                    listOfLists.add(list);
                }
            }   
    
            return listOfLists;
        }
    
        public static void main(String[] args) {
            List> permute = permute(1,2,3,4);
            System.out.println(permute);
        }
    
    }
    

    If you don't like the List> you can easily change from arrays to list using the methods from list and static methods from java.util.Collections and java.util.Arrays.

提交回复
热议问题