问题
If there is an array with elements: 1,2,3,4, the program should return another array with sum of all combinations:
1 2 3 4 3 (1+2) 4 (1+3) 5 (1+4) 5 (2+3) 6 (2+4) 7 (3+4) 6 (1+2+3) 7 (1+2+4) 8 (1+3+4) 9 (2+3+4) 10 (1+2+3+4)
回答1:
This is a function I wrote some time ago to generate all possible subsets of a given array. It's generic, so it supports integers, doubles, strings, etc.
Original C#
public static List<T[]> CreateSubsets<T>(T[] originalArray)
{
List<T[]> subsets = new List<T[]>();
for (int i = 0; i < originalArray.Length; i++)
{
int subsetCount = subsets.Count;
subsets.Add(new T[] { originalArray[i] });
for (int j = 0; j < subsetCount; j++)
{
T[] newSubset = new T[subsets[j].Length + 1];
subsets[j].CopyTo(newSubset, 0);
newSubset[newSubset.Length - 1] = originalArray[i];
subsets.Add(newSubset);
}
}
return subsets;
}
And the version I just converted to VB.
Function CreateSubsets(Of T)(ByVal originalArray() As T) As List(Of T())
Dim subsets As New List(Of T())
For i As Integer = 0 To originalArray.Length - 1
Dim subsetCount As Integer = subsets.Count
subsets.Add(New T() {originalArray(i)})
For j As Integer = 0 To subsetCount - 1
Dim newSubset(subsets(j).Length) As T
subsets(j).CopyTo(newSubset, 0)
newSubset(newSubset.Length - 1) = originalArray(i)
subsets.Add(newSubset)
Next
Next
Return subsets
End Function
It can be consumed in this manner
Dim array() As Integer = {1, 2, 3, 4, 5}
Dim subsets As List(Of Integer()) = CreateSubsets(array)
For Each subset As Integer() In subsets
Dim sum As Integer = subset.Sum()
Next
回答2:
My idea is:
(pseudcode, I don;t know VB)
for(int i = 0; i < 4321; i++)
{
i mod 10 + // first from right digit
(int)((i mod 100)mod 10) // second, (?)
// etc
// sum up all 4 digit
// add to array
}
回答3:
Coding the algorithm you mentioned in your comment, in pseudo VB code:
ReDim result(2 ^ (Length of Array) - 1)
for index = 0 to 2 ^ (Length of Array) - 1
sum = 0
for counter = 0 to (Length of Array) - 1
If ((2 ^ counter) And index) <> 0 Then
sum += Array(counter+1)
result(index) = sum
来源:https://stackoverflow.com/questions/2509436/how-to-make-all-possible-sum-combinations-from-array-elements-in-vb