一个算法题,是在想不出有什么好办法,求教
问题的原题是从1-10 10个数,要打印其 和为15的所有组合。这个题目非常简单,但是程序要求的是填充指定代码段实现,我想了半天都没法填充指定代码段实现,最后时间不够了,有人可以看看嘛?下面是我的实现,用了一个辅助函数,和题目要求不符。
题目的要求应该是填充getPrintNum( int n, int sum)这个函数,不能额外添加辅助函数
public class practiceString {
public static void main(String [] arg ) {
getPrintNum(10,15);
}
static void get_helpListNum(LinkedList<Integer> temp,int sum) {
if(temp.size() == 1 || sum == 0) {
if(sum == 0) {
System.out.println(_helplist.toString());
return;
}
if(sum == temp.get(0)){
_helplist.add(sum);
System.out.println(_helplist.toString());
_helplist.remove(_helplist.size() -1);
}
} else {
int nRemove = temp.size() - 1;
LinkedList<Integer> temp2 = new LinkedList<Integer>();
temp2.addAll(temp);
LinkedList<Integer>temp3 = new LinkedList<Integer>();
int nRemoveNum = temp2.remove(nRemove);
temp3.addAll(temp2);
if(sum - nRemoveNum < 0) {
get_helpListNum(temp3,sum);
} else {
_helplist.add(nRemoveNum);
get_helpListNum(temp2,sum - nRemoveNum);
_helplist.remove(_helplist.size() - 1);
get_helpListNum(temp3,sum);
}
}
}
static void getPrintNum( int n, int sum) {
LinkedList<Integer> temp = new LinkedList<Integer>();
for(int i = 1; i < n + 1; ++i) {
temp.add(i);
}
get_helpListNum(temp,sum);
}
public static LinkedList<Integer> _helplist;
static {
_helplist = new LinkedList();
}
}
题目的要求应该是填充getPrintNum( int n, int sum)这个函数,不能额外添加辅助函数
...全文


