慕勒3428872
private static List<int[]> samples(int n, int k) { if (k < 0 || n < 0) throw new IllegalArgumentException(); if (k == 0) return Collections.emptyList(); List<Integer> set = new ArrayList<>(); for (int i = 0; i < n; i++) set.add(i); if (k == 1) return set.stream().map(i -> new int[]{i}).collect(Collectors.toList()); List<int[]> previous = samples(n, k - 1); List<int[]> out = new ArrayList<>(); for (int i : set) for (int[] array : previous) out.add(glue(i, array)); return out;}private static int[] glue(int i, int[] array) { int[] out = new int[array.length + 1]; out[0] = i; System.arraycopy(array, 0, out, 1, array.length); return out;}例如,for (int[] sample : samples(2, 3)) { System.out.println(Arrays.toString(sample));}产量[0, 0, 0][0, 0, 1][0, 1, 0][0, 1, 1][1, 0, 0][1, 0, 1][1, 1, 0][1, 1, 1]和for (int[] sample : samples(4, 2)) { System.out.println(Arrays.toString(sample));}产量[0, 0][0, 1][0, 2][0, 3][1, 0][1, 1][1, 2][1, 3][2, 0][2, 1][2, 2][2, 3][3, 0][3, 1][3, 2][3, 3]
炎炎设计
检索到答案的第一个版本:您可以nn=(n+1)在每个r位置使用数字的变体,因此组合的总数为P = nn^r. 请注意,每个组合都对应于 range 中的数字0..P-1。因此,您可以遍历范围内的所有整数值0..P-1并表示 nn-ary 系统中的循环计数器。Java代码public static void main (String[] args) throws java.lang.Exception{ int n = 2; int r = 3; int nn = n + 1; int p = 1; for (int i=0; i<r; i++) p *= nn; for (int i=0; i<p; i++){ int t = i; String comb = "("; for (int j=0; j<r; j++){ comb = comb + String.format("%2d, ", t % nn); t = t / nn; } comb = comb.substring(0, comb.length()-2) + ')'; System.out.println(comb); }}蟒蛇代码:n = 2r = 3nn = n + 1p = nn**rfor V in range(p): t = V comb = [] for i in range(r): d = t % nn comb.append(d) t = t // nn print(comb)[0, 0, 0][1, 0, 0][2, 0, 0][0, 1, 0][1, 1, 0][2, 1, 0][0, 2, 0][1, 2, 0][2, 2, 0][0, 0, 1][1, 0, 1][2, 0, 1][0, 1, 1][1, 1, 1][2, 1, 1][0, 2, 1][1, 2, 1][2, 2, 1][0, 0, 2][1, 0, 2][2, 0, 2][0, 1, 2][1, 1, 2][2, 1, 2][0, 2, 2][1, 2, 2][2, 2, 2]第二个版本:用于替换组合。Python 中的递归(最简单的方式)生成。def cwrreq(maxlen, maxx, s): if len(s)== maxlen: print(s) else: for i in range(maxx + 1): cwrreq(maxlen, i, s + str(i))def combwithrepl(maxlen, maxval): cwrreq(maxlen, maxval, "")combwithrepl(3, 6)生成 84 种组合000100110111200...663664665666(3,3) 的完整列表。含义:有三个无法区分的盒子和三种颜料(比如红、绿、蓝)。000 all boxes are hollow100 one box is red110111 all boxes are red200210 one box is green, another is red211220221222300310311320321 all boxes have distinct colors322330331332333 all boxes are blue