一道面试题
有一个正整数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=15
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,"");
}
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)+"种");
}
}
}
}