你题目中说想要算法,所以我把m,n的值直接赋给了,如果需要的话可以改成从键盘录入。
public class HelloWorld
{
public static void main(String args[])
{
int[] shuzu = {1,2,3,4,5,6,7,8,9};//n=9,这里的n如果是需要手动输入的话,那么久生成新的数组,长度是n,然后依次赋值,你只是要算法,所以我把这里的n直接赋值了
int jieguo = 7;//这是你题目中的m的值
qiuHe(shuzu,jieguo);
}
public static void qiuHe(int[] shuzu,int jieguo)
{
int len = shuzu.length;
for(int m=0;m<len-1;m++)
{
for(int n=m+1;n<len;n++)
{
if((shuzu[m]+shuzu[n])==jieguo)
{
System.out.println("组合:"+shuzu[m]+"+"+shuzu[n]);
}
else if((shuzu[m]+shuzu[n])<jieguo)
{
int he = shuzu[m]+shuzu[n];
int[] arr = {shuzu[m],shuzu[n]};
qiuHe2(shuzu,n,he,jieguo,arr);
}
}
}
for(int x=0;x<len;x++)
{
if(shuzu[x]==jieguo)
{
System.out.println("组合:"+jieguo);
}
}
}
public static void qiuHe2(int[] shuzu,int kaishiweizhi,int he,int jieguo,int[] xinshuzu)//这个函数用来求出组合
{
for(int position=kaishiweizhi+1;position<shuzu.length;position++)
{
if((he+shuzu[position])==jieguo)
{
System.out.print("组合:");
for(int x=0;x<xinshuzu.length;x++)
{
System.out.print(xinshuzu[x]+"+");
}
System.out.println(shuzu[position]);
}
else if((he+shuzu[position])<jieguo)
{
int temp = xinshuzu.length+1;
int[] newarry = new int[temp];
for(int lennewarry=0;lennewarry<temp-1;lennewarry++)
{
newarry[lennewarry] = xinshuzu[lennewarry];
}
newarry[temp-1] = shuzu[position];
int he1 = he+shuzu[position];
qiuHe2(shuzu,position,he1,jieguo,newarry);
}
}
}
}
|