Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.List;
- public class Combinations {
- private final int n;
- private int x;
- private String[] disp;
- public static void main(String[] args) {
- System.out.println(new Combinations(8).generateAll());
- System.out.println(new Combinations(new String[] { "a", "b", "c" }).generateAll());
- }
- public Combinations(int n) {
- this.n = n;
- disp = new String[n];
- for (int i = 0; i < n; ++i) {
- disp[i] = Integer.toString(i + 1);
- }
- }
- public Combinations(String[] ss) {
- n = ss.length;
- disp = ss;
- }
- private int lowBit(int n) {
- return (1 << n) - 1;
- }
- private boolean next() {
- int smallest = x & -x;
- int ripple = x + smallest;
- int new_smallest = ripple & -ripple;
- int ones = ((new_smallest / smallest) >>> 1) - 1;
- x = ripple | ones;
- return (x & ~lowBit(n)) == 0;
- }
- public List<List<String>> generate(int k) {
- List<List<String>> ret = new ArrayList<>();
- x = lowBit(k);
- do {
- List<String> lis = new ArrayList<>();
- for (int s = x, i = 1; i <= n; s >>>= 1, ++i) {
- if ((s & 1) == 1) {
- lis.add(disp[i - 1]);
- }
- }
- ret.add(lis);
- } while (next());
- return ret;
- }
- public List<List<List<String>>> generateAll() {
- List<List<List<String>>> ret = new ArrayList<>();
- for (int i = 1; i <= n; ++i) {
- ret.add(generate(i));
- }
- return ret;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement