如何获得Java中具有重复项的所有组合(递归)? [英] How I can get all combinations that have duplicates in Java (recursion)?

查看:142
本文介绍了如何获得Java中具有重复项的所有组合(递归)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一种从这样的组合中删除重复项的方法:

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

输入: 3和2,其中3是范围(从1到3),而2是每种组合的长度

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

输出 {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,2} {2 ,3} {3,3}

所以我们从 {1,1}->开始{1,2}-> {1,3}-> ,但 {2,1} {1,2} ,所以我们忽略它,依此类推。

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.

这是我的代码:

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


推荐答案

您可以将上次使用的最大值传递给 gen

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

并以开头1 gen(0,1);

这篇关于如何获得Java中具有重复项的所有组合(递归)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆