有一個正整數x,和一個正整數集y,要求從y中取固定的個數z (能夠重複),相加以後的結果和爲x?編程實現
假如x=15 ,y集合爲{1,2,3,4,5,6,7,8,9}, z=5
求出知足全部的結果 編程
如
1+2+3+4+5=15
1+1+3+4+6=15get
public static void Main(String[] args) {
target = 15;
int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int count = 2;
getNumber(target, array, count,"");
}it
private static void getNumber(int target, int[] array, int count,String perfix) {
for (int i = 0; i < array.length; i++) {
if (count > 1) {
if (array[i] < target) {
Console.WriteLine(perfix+array[i]+"+" );
getNumber(target - array[i], array, count - 1,perfix+array[i]+"+");
}
} else {
if (target == array[i]) {
Console.Write(perfix+array[i] + "=");
Console.WriteLine(TestItractor.target+"這是第"+(++TestItractor.count)+"種");
}
}static
}
}集合