【问题标题】:How to save permutation in a Set Java如何在 Set Java 中保存排列
【发布时间】:2021-03-27 21:21:51
【问题描述】:

我有这个方法可以打印我用我的参数给出的 Set 的排列。但我需要将它们保存在 2 个单独的集合中并进行比较。因此,例如我有 [5,6,3,1] 和 [5,6,1,3],通过将它们添加到两个单独的 BST 中,我可以使用 compareTo 函数来比较它们,以检查它们的级别顺序是否为相同。但是我无法将这些排列从我的方法中保存到我的主要集合中。有谁知道如何将这些保存到集合中?

我现在拥有的:

import edu.princeton.cs.algs4.BST;

import java.util.*;

public class MyBST {
    public static void main(String[] args) {
        int size = 4;
        BST<Integer, Integer> bst1 = new BST<Integer, Integer>();
        BST<Integer, Integer> bst2 = new BST<Integer, Integer>();
        Random r = new Random();
        Set<Integer> tes = new LinkedHashSet<>(size);
        Stack<Integer> stack = new Stack<>();
        while (tes.size() < size) {
            tes.add(r.nextInt(10));
        }
        System.out.println(tes);
        System.out.println("possible combinations");
        Iterator<Integer> it = tes.iterator();
        for (int i = 0; i < tes.toArray().length; i++) {
            Integer key = it.next();
            bst1.put(key, 0);
        }
        combos(tes, stack, tes.size());
    }
}

这是我使用的方法:

public static void combos(Set<Integer> items, Stack<Integer> stack, int size) {
    if (stack.size() == size) {
        System.out.println(stack);
    }
    Integer[] itemz = items.toArray(new Integer[0]);
    for (Integer i : itemz) {
        stack.push(i);
        items.remove(i);
        combos(items, stack, size);
        items.add(stack.pop());
    }
}

这是输出:

【问题讨论】:

  • 请不要张贴文字图片;而是发布文本本身。

标签: java set permutation


【解决方案1】:

我不确定我是否理解你的想法,但也许这会有所帮助:

你的 combos 方法将返回所有排列的集合(作为堆栈)

...
        for (int i = 0; i < tes.toArray().length; i++) {
            Integer key = it.next();
            bst1.put(key, 0);
        }
        Set<Stack<Integer>> combos = combos(tes, stack, tes.size()); //there you have set with all Stacks
    }
}

    public static Set<Stack<Integer>> combos(Set<Integer> items, Stack<Integer> stack, int size) {
    Set<Stack<Integer>> set = new HashSet<>();

    if(stack.size() == size) {
        System.out.println(stack.to);
        set.add((Stack) stack.clone());
    }

    Integer[] itemz = items.toArray(new Integer[0]);
    for(Integer i : itemz) {
        stack.push(i);
        items.remove(i);
        set.addAll(combos(items, stack, size));
        items.add(stack.pop());
    }
    return set;
}

【讨论】:

    猜你喜欢
    • 2010-10-18
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    相关资源
    最近更新 更多