数组a[]={3,5,2,4,1,8},要求从a中找出所有“和”等于10的子集
有如下解决方案
public static void test(int []array){
int sum=0,index=-1 ;
Stack<Integer> c=new Stack<Integer>();
Stack<Integer>cIndex=new Stack<Integer>();//用于保存存入栈的数的下标
while(!c.isEmpty()||index!=array.length){
for(int i=index+1;i<array.length;i++){
if(sum+array[i]<=10){
c.push(array[i]);
sum+=array[i];
cIndex.push(i);
if(sum==10){
for(Integer k: c){
System.out.print(k+" ");
}
System.out.println();
break;
}
}
}
sum-=c.pop();
index=cIndex.pop();
}
}
/**递归法*/
public static void cal(int [] array,int from,int to){
if(sum==10){
for(Integer k: sk){
System.out.print(k+" ");
}
System.out.println( );
return ;
}
for(int j=from;j<to;j++){
if(sum+array[j]<=10){
sk.push(array[j]);
sum+=array[j];
cal(array,j+1,to);
sum-=sk.pop();
}
}
}