在一个整数数组(没有重复数字)中,找出和为目标值的数字
public String test(int[] n,int dest){
List<String> list = new ArrayList<String>();
List<String> tmp = new ArrayList<String>();
StringBuffer buf = new StringBuffer();
test4(list, tmp,n, dest,0,buf);
//System.out.println(buf.toString());
return buf.toString();
}
static void test2(List<String> list,List<String> tmp,int[] n,
int dest,int start,StringBuffer result){
//如果目标值已经小于0,则直接返回
if(dest < 0){
return;
}
//如果目标值等于0,说明已经找到合适的数字组合
if(dest == 0){
list.addAll(tmp);
result.append(list.toString());
//将数字组合加到结果集合中,然后清空链表
list.clear();
}else {
for(int i=start; i<n.length; i++){
//将当前数字加到链表中
tmp.add(""+n[i]);
//递归调用,目标值减去当前数字
test2(list, tmp,n, dest-n[i],i,result);
//将最后一个数字从链表中删去
tmp.remove(tmp.size()-1);
}
}
}
在一个整数数组(如果存在重复数字)中,找出和为目标值的数字
public String test(int[] n,int dest){
List<String> list = new ArrayList<String>();
List<String> tmp = new ArrayList<String>();
StringBuffer buf = new StringBuffer();
//将数组排序
Arrays.sort(n);
test4(list, tmp,n, dest,0,buf);
//System.out.println(buf.toString());
return buf.toString();
}
static void test2(List<String> list,List<String> tmp,int[] n,
int dest,int start,StringBuffer result){
//如果目标值已经小于0,则直接返回
if(dest < 0){
return;
}
//如果目标值等于0,说明已经找到合适的数字组合
if(dest == 0){
list.addAll(tmp);
result.append(list.toString());
//将数字组合加到结果集合中,然后清空链表
list.clear();
}else {
for(int i=start; i<n.length; i++){
if(i>start && n[i] == n[i-1]){
continue; //跳过重复数字
}
//将当前数字加到链表中
tmp.add(""+n[i]);
//递归调用,目标值减去当前数字
test2(list, tmp,n, dest-n[i],i,result);
//将最后一个数字从链表中删去
tmp.remove(tmp.size()-1);
}
}
}