给定一个整数数组和一个整数k, 编写一个函数来检查数组中是否存在一组数字,它们的总和等于k。
让我对这个问题感兴趣的是,可以从数组中的两个以上数字中求和。
例如:
Arr [5,4,3,7]
k = 16
输出:true // 5 + 7 + 4 = 16
答案 0 :(得分:0)
请注意,此回答仅对此类问题有用。不要忽略查看其他用户的提示
private int[] givenArrayOfIntegers = new int[]{5, 4, 3, 7};
private void find(List<Integer> passedIndexes, int fromIndex, int requiredSum) {
// used java 8th stream opportunities.
// Can be replaced with good old for loop
int sumOfThePreviousElements = passedIndexes.stream()
.mapToInt(i -> givenArrayOfIntegers[i]).sum();
// iterate over leftover elements
for (int i = fromIndex; i < givenArrayOfIntegers.length; i++) {
if (sumOfThePreviousElements + givenArrayOfIntegers[i] == requiredSum) {
// we've found the subset
// here I just print values to the output,
// your preferences may be different
passedIndexes.forEach(k -> System.out.print(givenArrayOfIntegers[k] + ", "));
System.out.println(givenArrayOfIntegers[i]);
} else if (sumOfThePreviousElements + givenArrayOfIntegers[i] < requiredSum) {
// if sum of the elements less than required try to call this method again
// with complemented 'i' value
passedIndexes.add(i);
// (RECURSION IS HERE)
find(passedIndexes, i + 1, requiredSum);
// remove for the next loop purposes
passedIndexes.remove(passedIndexes.size() - 1);
}
}
}
答案 1 :(得分:0)
我从下面的链接中找到了
https://www.geeksforgeeks.org/perfect-sum-problem-print-subsets-given-sum/
您可以尝试一下吗?
class Program
{
static bool[][] boolean;
static string Output = "";
static int Sum1 = 0;
static void Main(string[] args)
{
List<int> abc = new List<int>();
int[] arr = { 5, 4, 3, 7 };
int n = arr.Length;
int sum = 16;
bool[][] ServicePoint = new bool[n][];
for (var i = 0; i < ServicePoint.Length; i++)
{
ServicePoint[i] = new bool[sum + 1];
}
boolean = ServicePoint;
int z = 0;
while (z < n)
{
boolean[z][0] = true;
++z;
}
boolean[0][arr[0]] = arr[0] <= sum ? true : false;
for (int i = 1; i < n; ++i)
{
for (int j = 0; j < sum + 1; ++j)
{
if (arr[i] <= j)
{
boolean[i][j] = boolean[i - 1][j] || boolean[i - 1][j - arr[i]];
}
else
{
boolean[i][j] = boolean[i - 1][j];
}
}
}
displayOutput(arr, n - 1, sum, abc);
Console.ReadLine();
}
static void displayOutput(int[] arr, int i, int sum, List<int> abc)
{
if (i == 0 && sum == 0)
{
Output = String.Join(" + ", abc);
Sum1 = abc.Sum();
Console.WriteLine("Sum of numbers: " + Output + " = " + Sum1);
Console.WriteLine("-----------------------------------");
abc.Clear();
return;
}
if (i == 0 && sum != 0 && boolean[0][sum])
{
abc.Add(arr[i]);
Output = String.Join(" + ", abc);
Sum1 = abc.Sum();
Console.WriteLine("Sum of numbers: " + Output + " = " + Sum1);
Console.WriteLine("-----------------------------------");
abc.Clear();
return;
}
if (boolean[i - 1][sum])
{
List<int> b = new List<int>();
b.AddRange(abc);
displayOutput(arr, i - 1, sum, b);
}
if (sum >= arr[i] && boolean[i - 1][sum - arr[i]])
{
abc.Add(arr[i]);
displayOutput(arr, i - 1, sum - arr[i], abc);
}
}
}