我需要找到一种从这样的组合中删除重复项的方法:
输入: 3和2,其中3是范围(从1到3),2是每种组合的长度
输出 :{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}
预期产量 :{1, 1} {1, 2} {1, 3} {2, 2} {2, 3} {3, 3}
{1, 1} {1, 2} {1, 3} {2, 2} {2, 3} {3, 3}
因此,我们从开始{1, 1} -> {1, 2} -> {1, 3} ->但是{2, 1}的重复项,{1, 2}因此我们将其忽略,依此类推。
{1, 1} -> {1, 2} -> {1, 3} ->
{2, 1}
{1, 2}
这是我的代码:
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:
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);
1
gen(0, 1);