簡體   English   中英

如何從 n 位數字中獲得 n/2 位數字組合

[英]How to get n/2-digit combinations from n digit number

我正在努力解決這個算法。 它應該像這樣工作:

如果我輸入 fe 6880,我的程序應該輸出 80 86 80 86 60 68 68。

如您所見,組合不斷重復。 那是因為它查看每個數字,因為它是一個不同的對象。 在我的程序中它是正確的。

這是我的代碼:

public static Set<Integer> get2DCombinations(List<Integer> digits) {
    Set<Integer> combinations = new TreeSet<>();

    int t = 0;
    for(Integer i : digits) {
        for (Integer j : digits) {
            t = i * 10 + j;
            if (t / 10 >= 1) {
                combinations.add(t);
            }
        }
    }

    return combinations;
}

它返回一組特定的組合,其中所有組合都有 2 位數字。

它工作得很好,但只能使用 4 位數字。 當然,我可以再使用一個 for-each 循環,但是有沒有辦法讓它自動化?

所以如果我輸入 6 位數字,它應該輸出所有可能的 3 位數字組合,如果我輸入 8 位數字,它應該輸出所有可能的 4 位數字組合。 輸入數字總是偶數位數。

你能幫我指出怎么做嗎?

您需要一個遞歸程序來為您的輸入生成所有組合。 這是我的一個解決方案。 我的方法接受一個String作為輸入(它只是一個簡短的程序,更簡單,您可以根據自己的需要進行調整):

public static Set<String> get2DCombinations(String input) {
    return backtracking("", input, input.length() / 2) ;
}

public static Set<String> backtracking(String actual, String remaining, int length) {
    if (actual.length() == length) {
        return new HashSet<>(Arrays.asList(actual));
    }

    Set<String> result = new HashSet<>();
    for(int i = 0; i < remaining.length(); i++) {
        result.addAll(backtracking(actual + remaining.charAt(i), remaining.substring(0, i) + remaining.substring(i + 1), length));
    }
    return result;
}

你像這樣調用方法:

System.out.println(get2DCombinations(input));

結果:

[88, 68, 06, 80, 08, 60, 86]

正如我在評論中提到的,您缺少一些組合。 此解決方案生成所有這些。

首先嘗試計算 n / 2。 因此,如果 n 為 6,則 n / 2 = 3。那么您在開始對組合進行優化之前就知道您正在尋找 3 位數字的組合。 然后你想找到合適的算法來找到組合。 解決問題的一部分是將問題分解為更小的問題。 這就是我在這里所做的。 但是,我無法為您解決,因為您自己解決更好,其次,您沒有提供詳細信息,因此很難給出正確的解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM