简体   繁体   English

递归问题 - 给定数组 n 和数字 k

[英]Recursion Problem - given array n and a number k

Given an array size n, and a positive number max(max represent the range of the numbers that we can use to place in the array).给定一个数组大小 n 和一个正数 max(max 表示我们可以用来放置在数组中的数字的范围)。

I would like to count how many combinations of sorted numbers I can place in the array.我想计算我可以在数组中放置多少个排序数字组合。

For example :例如 :

If n = 3, max = 2 .(the only numbers we can use is 1/2 as max is 2) so there are 4 combinations of sorted arrays如果n = 3, max = 2 .(我们可以使用的唯一数字是 1/2,因为 max 是 2)所以有 4 种排序数组的组合

 1. {1,1,1}
 2. {1,1,2}
 3. {1,2,2}
 4. {2,2,2}

I wrote some code and succeed to pass this specific example but any other example that max > 2 doesn't return the correct answer.我写了一些代码并成功通过了这个特定的例子,但是max > 2任何其他例子都没有返回正确的答案。

the problem as I identify it is when the recursion reaches the last index it doesn't try a third number it just folds back.我发现的问题是当递归到达最后一个索引时,它不会尝试第三个数字,它只是折回。

my code :我的代码:

private static int howManySorted(int n, int max, int index, int numToMax, int prevNum) {        
    // If the value is bigger then max return 0
    if(numToMax > max) {
        return 0;
    }
    if (numToMax < prevNum) {
        return 0;
    }
    //If Index reached the end of the array return 1
    if(index == n) {
        return 1;
    }

    int sortTwo =  howManySorted(n, max, index+1, numToMax, numToMax);
    int sortOne =  howManySorted(n, max, index+1, numToMax+1, numToMax);
    return ((sortOne+sortTwo));
}

public static int howManySorted(int n, int max) {
    return howManySorted(n, max, 0, 1, 0);
}

start with "{1," and add elements "{1,1" and/or value "{2," with each recursion.以“{1”开头,并在每次递归时添加元素“{1,1”和/或值“{2”。 when it reach n elements array we add to the counter.当它到达 n 个元素数组时,我们将其添加到计数器中。 n is the number of elements in the array max is the maximal value for each element. n 是数组中的元素数 max 是每个元素的最大值。 minimal is 1. element is the current cell in the array being manipulated.最小为 1。 element 是正在操作的数组中的当前单元格。 we start with 1 (in actual array means 0).我们从 1 开始(在实际数组中意味着 0)。 value is the current value of the current element. value 是当前元素的当前值。 we start with 1.我们从 1 开始。

// external function according to the given question
public static int count (int n, int max) 
{
    return count(n,max, 1, 1);
}

private static int count (int n, int max, int element, int value) 
{
    int counter = 0;
    // only if our array reached n elements we count the comination
    if (element == n) 
        counter++;
    else // we need to continue to the next element with the same value
        counter += count(n, max, element +1, value);
    if (value < max) // if our current element didn't reach max value
        counter += count (n, max, element, value+1); 
    return counter;
}

I think you would need to change your two recursive calls (this is why it only reaches value 2) and do as many calls as your max parameter:我认为您需要更改您的两个递归调用(这就是它只达到值 2 的原因)并执行与max参数一样多的调用:

private static int howManySorted(int n, int max, int index, int numToMax, int prevNum) {
    // If the value is bigger then max return 0
    if (numToMax > max) {
        return 0;
    }
    if (numToMax < prevNum) {
        return 0;
    }
    //If Index reached the end of the array return 1
    if (index == n) {
        return 1;
    }

    int result = 0;
    for (int i = 0; i < max; i++)
        result += howManySorted(n, max, index + 1, numToMax + i, numToMax);

    return result;
}

I believe you can simplify your answer to something like this我相信你可以简化你对这样的回答

private static long howManySorted(int length, int min, int max) {
    if (length == 1) {
        return max - min + 1;
    }

    // if (min == max) {
    //    return 1;
    // }

    long result = 0;
    for (int i = min; i <= max; i++) {
        result += howManySorted(length - 1, i, max);
    }
    return result;
}

public static long howManySorted(int length, int max) {
    if ((length < 1) || (max < 1)) {
        throw new IllegalArgumentException();
    }

    return howManySorted(length, 1, max);
}

Client should call the public method.客户端应该调用public方法。

So as you can see terminate conditions are when remaining length is 1, or min reaches max .因此,您可以看到终止条件是剩余length为 1 或min达到max Even removing the second terminate condition doesn't change the result, but can improve the performance and number of recursions.即使删除第二个终止条件也不会改变结果,但可以提高性能和递归次数。

Just test my code, I think it figures out your problem:只需测试我的代码,我认为它可以解决您的问题:

class Test {
private static int howManySorted(int n, int max) {
    //Better time complexity if u use dynamic programming rather than recursion.

    if (n == 0) return 1;

    int res = 0; // "res" can be a very large.

    for (int i = n; i >= 1; i--) {
        for (int j = max; j >= 1;j--) {
            res += howManySorted(i-1, j-1);
        }
    }

    return res;
}

public static void main(String[] args) {
    System.out.println(howManySorted(3, 2));
}

} }

This code will run faster if you use dynamic programming and be careful about the answer, it could be a very large integer.如果您使用动态编程并注意答案,此代码将运行得更快,它可能是一个非常大的整数。

You guys are forgetting he needs a solution using only recursion.你们忘记了他只需要使用递归的解决方案。 Probably a Java assignment for a CS class.可能是 CS 类的 Java 作业。

I also had that question.我也有这个疑问。

This is the answer I came up with:这是我想出的答案:

/**
 * @param n Number of values in the array
 * @param max Maximum value of each cell in the array
 * @return int
 */
public static int howManySorted(int n, int max) {
    return howManySorted(max, max, 1, n - 1);
}

/**
 *
 * @param value The current value
 * @param max The maximum possible value (not allowed to use global parameters, so the parameter value always stays the same)
 * @param min The minimum value allowed in this index. Determined by the value of the previous index (when first called, use value 1)
 * @param index The index of the value being manipulated
 * @return
 */
public static int howManySorted(int value, int max, int min, int index) {
    //If any of these cases are found true, it means this value is invalid, don't count it
    if (index < 0 || value < min) {
        return 0;
    }
    //First lower the value in the same index, the result is the number of valid values from that branch
    int lowerValue = howManySorted(value - 1, max, min, index);
    //Now check all the valid values from the next index - value is max-1 to prevent counting twice some numbers
    int lowerIndex = howManySorted(max - 1, max, value, index - 1);
    //Return 1 (this number we are at right now) + all of its children
    return 1 + lowerValue + lowerIndex;
}

I treated each series (eg '1,1,2') as an array, so at the beginning I wrote something like that:我将每个系列(例如'1,1,2')视为一个数组,所以一开始我写了这样的东西:

public static void main(String[] args)
{
    System.out.println(howManySorted(3, 2, 1, "")); // 4
    System.out.println(howManySorted(2, 3, 1, "")); // 6
}
private static int howManySorted(int n, int max, int index, String builder)
{
    if (max == 0) // if we exceeds max, return 0.
        return 0;

    if (n == 0) // num represents how many individual numbers we can have, if it is zero it means we have the required length (e.g. if n = 3, we have 'x1,x2,x3').
    {
        System.out.println(builder.substring(0, builder.length() - 2));
        return 1;
    }

    int r1 = howManySorted(n - 1, max, index, builder + index + ", "); // i added additional var 'index' to represent each number in the list: (1,1,1)
    int r2 = howManySorted(n, max - 1, index + 1, builder); // I'm increasing the index and decreasing the max (1,1,**2**)

    return r1 + r2;
}

But eventually, we don't need the 'index' nor the 'builder', they were just to emphasize how I solved it...但最终,我们不需要“索引”或“构建器”,它们只是为了强调我是如何解决它的……

public static void main(String[] args)
{
    int max = 2, n = 3;
    System.out.println(howManySorted(n, max)); // 4

    int max1 = 3, n1 = 2;
    System.out.println(howManySorted(n1, max1)); // 6
}

public static int howManySorted(int n, int max)
{
    if (max == 0) // if we exceeds max, return 0.
        return 0;

    if (n == 0) // like we said, num represents how many individual numbers we can have, if it is zero it means we have the required length (e.g. if n = 3, we have 'x1,x2,x3').
        return 1;

    int r1 = howManySorted(n - 1, max);
    int r2 = howManySorted(n, max - 1);

    return r1 + r2;
}

暂无
暂无

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

相关问题 给定一个由 N 个整数组成的数组 A,返回最大的整数 K&gt;0,使得数组 A 中同时存在 K 和 -K(相反的数) - given an array A of N integers, return the largest integer K>0 such that both K and -K(the opposite number) exist in array A 给定n作为项数的系列的总和(递归) - Summation of a series given n as number of terms (recursion) 给定数字N,如何调用递归调用N次? - how to call a recursion call N number of times, given the number N? 使用Java中的递归计算数组中大小为k的组合总数? - Calculate total number of combinations of size k in array using recursion in Java? 鉴于0 &lt; k &lt; n,并且在java中的O(k log n)时间,如何在大小为n的排序数组中获得超过n / k次的任何integer? - how to get any integer in a sorted array of size n that appear more than n/k times, given that 0 < k < n, and in O(k log n) time in java? 计算可被给定查询 k 整除的数组中的整数数 - Count the number of integers in an array divisible by a given query k 给定 k,使用递归求几何和 - With given k, find the geometric sum using recursion 在 O(n log n) 时间内生成具有 n 个长度和 k 个反转的数组的算法? - Algorithm to generate an array with n length and k number of inversions in O(n log n) time? 如何理解给定的递归问题? - How to understand given recursion problem? 大小为N的给定数组之间的k个空格之间的n个数字的最小和 - Minimum sum of n numbers with k spaces in between of a given array of size N
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM