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

zhengwei060024 2018-12-20 08:19:37
问题的原题是从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)这个函数,不能额外添加辅助函数
...全文
121 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_32270433 2018-12-20
  • 打赏
  • 举报
回复
static void getPrintNum(int n, int sum) {
Stack<Integer> stack = new Stack<Integer>();
for (int i = 1; i <= n / 2; i++) {
int tempSum = sum;
stack.push(i);
tempSum = sum - i;
int popNum = i;
while (!stack.isEmpty()) {
popNum++;
if (tempSum > popNum * 2) {
stack.push(popNum);
tempSum -= popNum;
} else if (tempSum == popNum) {
stack.push(popNum);
System.out.println(stack.toString());
stack.pop();
popNum = stack.pop();
tempSum += popNum;
} else if (tempSum < popNum || popNum == 10) {
popNum = stack.pop();
tempSum += popNum;
}
}
}
}

50,544

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧