【问题标题】:Minimum count of numbers required from given array to represent S给定数组表示 S 所需的最小数字计数
【发布时间】:2021-09-24 19:30:39
【问题描述】:

给定一个整数 S 和一个数组 arr[],任务是找到和为 S 的元素的最小数量,使得数组中的一个元素只能被选择一次以获得和 S。

示例:

Input: arr[] = {25, 10, 5}, S = 30 
Output: 2 

说明:

Minimum possible solution is 2, (25+5)

示例:

Input: arr[] = {2, 1, 4, 3, 5, 6}, Sum= 6 
Output: 1 

说明:

Minimum possible solution is 1, (6)

我找到了类似的解决方案here,但它说数组元素可以多次使用。

我从链接中获得了这段代码,它多次使用了一个数组元素,但是如何限制它只使用一次呢?

static int Count(int S[], int m, int n)
{
    int [][]table = new int[m + 1][n + 1];
 
    // Loop to initialize the array
    // as infinite in the row 0
    for(int i = 1; i <= n; i++)
    {
    table[0][i] = Integer.MAX_VALUE - 1;
    }
 
    // Loop to find the solution
    // by pre-computation for the
    // sequence
    for(int i = 1; i <= m; i++)
    {
    for(int j = 1; j <= n; j++)
    {
        if (S[i - 1] > j)
        {
            table[i][j] = table[i - 1][j];
        }
        else
        {
                 
            // Minimum possible for the
            // previous minimum value
            // of the sequence
            table[i][j] = Math.min(table[i - 1][j],
                            table[i][j - S[i - 1]] + 1);
        }
    }
    }
    return table[m][n];
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 9, 6, 5, 1 };
    int m = arr.length;
     
    System.out.print(Count(arr, m, 11));
}

【问题讨论】:

    标签: java arrays algorithm


    【解决方案1】:

    对此的惯用方法是在更新先前结果表时向后循环。

    static int minElementsForSum(int[] elems, int sum){
        int[] minElems = new int[sum + 1];
        for(int i = 1; i <= sum; i++) minElems[i] = Integer.MAX_VALUE;
        for(int elem: elems) 
            for(int i = sum; i >= elem; i--) 
                if(minElems[i - elem] != Integer.MAX_VALUE) 
                  minElems[i] = Math.min(minElems[i], minElems[i - elem] + 1);
        return minElems[sum];
    }
    

    Demo

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 2020-11-28
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多