简体   繁体   English

Integer 的降序排列

[英]Permutation of a Integer in descending order

I am trying to return the permutations of an integer in descending order.我正在尝试按降序返回 integer 的排列。 Currently I have code which returns all the permutations of a number however, it is not in descending order.目前我有返回一个数字的所有排列的代码,但是它不是按降序排列的。 I am unsure to whether I should use an array instead and it may be easier.我不确定是否应该使用数组,它可能更容易。 My current code is:我目前的代码是:

// 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);
    }
}

You can use global List<String> permutations then put all values into this collection您可以使用全局List<String> permutations ,然后将所有值放入此集合
Finally, you can sort it in a descending order using最后,您可以使用降序对其进行排序
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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM