双数据类型的子集和?

hfyxw5xn  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(287)

我有以下代码的子集和这是适合整数。如何将此代码扩展到双数据类型输入?例如,当输入为1.01,2.65,3.08,4.07,5.12(假设),输出为15.62(假设)时,如何扩展相同的代码。这些输入和输出都是示例,即使它们改变了代码也应该工作。

// A Java program to count all subsets with given sum.
import java.util.ArrayList;
public class subset_sum
{
// dp[i][j] is going to store true if sum j is
// possible with array elements from 0 to i.
static boolean[][] dp;

static void display(ArrayList<Integer> v)
{
    System.out.println(v);
}

// A recursive function to print all subsets with the
// help of dp[][]. Vector p[] stores current subset.
static void printSubsetsRec(int arr[], int i, int sum,
                            ArrayList<Integer> p)
{
    // If we reached end and sum is non-zero. We print
    // p[] only if arr[0] is equal to sun OR dp[0][sum]
    // is true.
    if (i == 0 && sum != 0 && dp[0][sum])
    {
        p.add(arr[i]);
        display(p);
        p.clear();
        return;
    }

    // If sum becomes 0
    if (i == 0 && sum == 0)
    {
        display(p);
        p.clear();
        return;
    }

    // If given sum can be achieved after ignoring
    // current element.
    if (dp[i-1][sum])
    {
        // Create a new vector to store path
        ArrayList<Integer> b = new ArrayList<>();
        b.addAll(p);
        printSubsetsRec(arr, i-1, sum, b);
    }

    // If given sum can be achieved after considering
    // current element.
    if (sum >= arr[i] && dp[i-1][sum-arr[i]])
    {
        p.add(arr[i]);
        printSubsetsRec(arr, i-1, sum-arr[i], p);
    }
}

// Prints all subsets of arr[0..n-1] with sum 0.
static void printAllSubsets(int arr[], int n, int sum)
{
    if (n == 0 || sum < 0)
        return;

    // Sum 0 can always be achieved with 0 elements
    dp = new boolean[n][sum + 1];
    for (int i=0; i<n; ++i)
    {
        dp[i][0] = true;
    }

    // Sum arr[0] can be achieved with single element
    if (arr[0] <= sum)
        dp[0][arr[0]] = true;

    // Fill rest of the entries in dp[][]
    for (int i = 1; i < n; ++i)
        for (int j = 0; j < sum + 1; ++j)
            dp[i][j] = (arr[i] <= j) ? (dp[i-1][j] ||
                    dp[i-1][j-arr[i]])
                    : dp[i - 1][j];
    if (dp[n-1][sum] == false)
    {
        System.out.println("There are no subsets with" +
                " sum "+ sum);
        return;
    }

    // Now recursively traverse dp[][] to find all
    // paths from dp[n-1][sum]
    ArrayList<Integer> p = new ArrayList<>();
    printSubsetsRec(arr, n-1, sum, p);
}

//Driver Program to test above functions
public static void main(String args[])
{
    int arr[] = {1, 2, 3, 4, 5};
    int n = arr.length;
    int sum = 10;
    printAllSubsets(arr, n, sum);
}
}

输出:[4,3,2,1][5,3,2][5,4,1]

cidc1ykv

cidc1ykv1#

我找到了这个问题的答案,简单地将double转换成整数,通过计算小数位数并将其乘以100(比如说),因为算法使用加法这个更改不会影响最终值,在这种情况下,我将最终值除以100得到结果,并以double数据类型显示它

相关问题