简体   繁体   English

我如何获得在 Java 中具有重复项的所有组合(递归)?

[英]How I can get all combinations that have duplicates in Java (recursion)?

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输入: 3 和 2,其中 3 是范围(从 1 到 3),2 是每个组合的长度

Output : {1, 1} {1, 2} {1, 3} {2, 1} {2, 2} {2, 3} {3, 1} {3, 2} {3, 3}输出{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}预期输出{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.所以我们从{1, 1} -> {1, 2} -> {1, 3} ->但是{2, 1}{1, 2}的副本,所以我们忽略它等等。

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);
    }
}

You can pass the last max value used into gen :您可以将使用的最后一个最大值传递给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);并从1开始调用它: gen(0, 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM