How to iteratively generate k elements subsets from a set of size n in java?

后端 未结 7 1761
忘掉有多难
忘掉有多难 2020-11-29 09:14

I\'m working on a puzzle that involves analyzing all size k subsets and figuring out which one is optimal. I wrote a solution that works when the number of subsets is small,

相关标签:
7条回答
  • 2020-11-29 10:02

    You can use org.apache.commons.math3.util.Combinations.

    Example:

    import java.util.Arrays;
    import java.util.Iterator;
    
    import org.apache.commons.math3.util.Combinations;
    
    public class tmp {
        public static void main(String[] args) {
            for (Iterator<int[]> iter = new Combinations(5, 3).iterator(); iter.hasNext();) {
                System.out.println(Arrays.toString(iter.next()));
            }
        }
    
    }
    

    Output: [0, 1, 2] [0, 1, 3] [0, 2, 3] [1, 2, 3] [0, 1, 4] [0, 2, 4] [1, 2, 4] [0, 3, 4] [1, 3, 4] [2, 3, 4]

    0 讨论(0)
提交回复
热议问题