Split a list into two sublists in all possible ways

前端 未结 4 973
情深已故
情深已故 2020-12-08 22:42

I have a list of variable size, for example

[1, 2, 3, 4]

and I want to get every possible way to split this list into two:

         


        
4条回答
  •  感情败类
    2020-12-08 23:04

    Though in Python, it's quite easy to get the result with its extensive library, in Java, you can write a recursive solution. The following will print all possible combinations of your array:

    public static void main(String[] args) {
        List num = Arrays.asList(1, 2, 3, 4);
        List> sublists = new ArrayList>();
        for (int i = 0; i <= num.size(); i++) {
          permutation(num, sublists, i, new ArrayList(), 0);
        }
    
        for (List subList : sublists) {
            List numCopy = new ArrayList(num);
            numCopy.removeAll(subList);
            System.out.println("(" + subList + ", " + numCopy + ")");
        }
    }
    
    public static void permutation(List nums, List> subLists, int sublistSize, List currentSubList,
          int startIndex) {
        if (sublistSize == 0) {
          subLists.add(currentSubList);
        } else {
          sublistSize--;
          for (int i = startIndex; i < nums.size(); i++) {
            List newSubList = new ArrayList(currentSubList);
            newSubList.add(nums.get(i));
            permutation(nums, subLists, sublistSize, newSubList, i + 1);
          }
        }
    }
    

    The sublists carries all the combinations found till now. The last parameter is the startIndex for the next element of current sublist. That is to avoid duplicates.

提交回复
热议问题