遇到个问题:数组里任意个数数字相加等于一固定数值
于是自己用java实现了,欢迎大家提出更好的方法
public class SumTest {
static final int SUM = 20;
public static void getSum(int data[], List list, int pos){
if(pos >= data.length){
return;
}
//System.out.println("getSum:" + pos);
list.add(pos);
int sum=0;
for (Integer integer : list) {
sum += data[integer];
}
if(sum
getSum(data, list, pos+1);
}else{
int npos;
if(sum==SUM){
StringBuilder builder = new StringBuilder();
for (Integer integer : list) {
builder.append(data[integer]+",");
}
System.out.println("find:"+builder.toString());
npos = list.remove(list.size()-1);
if(list.size()==0){
npos++;
}
}else{
npos = list.remove(list.size()-1);
if(list.size()==0){
npos++;
}else{
npos = list.remove(list.size()-1);
}
}
getSum(data, list, npos+1);
}
}
public static void main(String[] args) {
int data[] = new int[20];
for(int i=0; i
data[i]=i+1;
}
List list = new ArrayList();
getSum(data,list, 0);
}
}
阅读(8903) | 评论(0) | 转发(0) |