一个算法题,是在想不出有什么好办法,求教

zhengwei060024 zhengwei060024 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
问题的原题是从1-10 10个数,要打印其 和为15的所有组合。这个题目非常简单,但是程序要求的是填充指定代码段实现,我想了半天都没法填充指定代码段实现,最后时间不够了,有人可以看看嘛?下面是我的实现,用了一个辅助函数,和题目要求不符。
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)这个函数,不能额外添加辅助函数
...全文
评论 1
收藏 已收藏
分享
返回顶部
zhengwei060024
Java 51,407 成员 86,172 内容