How I can get all combinations that have duplicate

2019-02-25 15:37发布

I need to find a way to remove duplicates from a combination like this:

Input: 3 and 2, where 3 is the range (from 1 to 3) and 2 is the length of each combination

Output: {1, 1} {1, 2} {1, 3} {2, 1} {2, 2} {2, 3} {3, 1} {3, 2} {3, 3}

Expected output: {1, 1} {1, 2} {1, 3} {2, 2} {2, 3} {3, 3}

So we start with {1, 1} -> {1, 2} -> {1, 3} -> but {2, 1} is a duplicate of {1, 2} so we ignore it and so on.

Here's my code:

import java.util.Scanner;

public class Main {
    private static int[] result;
    private static int n;

    private static void printArray() {
        String str = "( ";
        for (int number : result) {
            str += number + " ";
        }
        System.out.print(str + ") ");
    }

    private static void gen(int index) {
        if (index == result.length) {
            printArray();
            return;
        }
        for (int i = 1; i <= n; i++) {
            result[index] = i;
            gen(index + 1);
        }
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("From 1 to: ");
        n = input.nextInt();
        System.out.print("Length: ");
        int k = input.nextInt();

        result = new int[k];

        gen(0);
    }
}

1条回答
萌系小妹纸
2楼-- · 2019-02-25 15:58

You can pass the last max value used into gen:

private static void gen(int index, int minI) {
    if (index == result.length) {
        printArray();
        return;
    }
    for (int i = minI; i <= n; i++) {
        result[index] = i;
        gen(index + 1, i);
    }
}

And call it starting with 1: gen(0, 1);

查看更多
登录 后发表回答