我试图按降序返回整数的排列。当前,我有返回数字的所有排列的代码,但是它不是降序排列的。我不确定是否应该使用数组,这可能会更容易。我当前的代码是:

// Function to print all the permutations of str
static void printPermutn(String str, String ans)
{
    // If string is empty
    if (str.length() == 0) {
        System.out.print(ans + " ");
        return;
    }

    for (int i = 0; i < str.length(); i++) {

        // 1st character of str
        char ch = str.charAt(i);

        // Rest of the string after excluding
        // the 1st character
        String ros = str.substring(0, i) +
                str.substring(i + 1);

        // Recurvise call

        printPermutn(ros, ans + ch);
    }
}

最佳答案

您可以使用全局List<String> permutations,然后将所有值放入此集合中
最后,您可以使用降序对它进行排序
Collections.sort(permutations, Collections.reverseOrder());

private static List<String> permutations;

public static void main(String[] args) {
    permutations = new ArrayList<>();
    printPermutn("123", "");

    System.out.println();
    System.out.println("permutations BEFORE sorting");
    System.out.println(permutations);

    // sort
    Collections.sort(permutations, Collections.reverseOrder());

    System.out.println("permutations AFTER sorting");
    System.out.println(permutations);
}

// Function to print all the permutations of str
static void printPermutn(String str, String ans) {
    // If string is empty
    if (str.length() == 0) {
        System.out.print(ans + " ");
        permutations.add(ans);
        return;
    }

    for (int i = 0; i < str.length(); i++) {

        // 1st character of str
        char ch = str.charAt(i);

        // Rest of the string after excluding
        // the 1st character
        String ros = str.substring(0, i) + str.substring(i + 1);

        // Recurvise call

        printPermutn(ros, ans + ch);
    }
}

关于java - 整数的降序排列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58293789/

10-10 18:32