本帖最后由 梁永奇 于 2013-1-30 04:00 编辑
我把代码简化了,所以上面的代码看起来比较费劲,我把最初写的代码给你复制过来吧。你题目中的意思,应该是不需要去重的
package cn.itcast;
public class HelloWorld
{
public static void main(String args[])
{
int[] shuzu = {2,6,9,4,0,1,8,2,7,2,2,4,2,1,1,1,1};//这是你题目中的n个整数,我放在了数组中
int jieguo = 8;//这是你题目中的t
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);
}
}
}
}
|