public static void main(String[] args){
int n = 5;
// 最多可以由n个数组成 最少可以由一个数组成
for (int i = n; i > 0 ; i--) {
myDfsII(1,n,i,new LinkedList<Integer>());
}
}
/*
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5
*/
/**
* @param start 起始数
* @param target 目标树
* @param needCount 还差几个数
* @param list
*/
public static void myDfsII(int start, int target, int needCount, LinkedList<Integer> list) {
if (needCount == 1){
// 注意这里不能是直接out.add(list) 想想为什么
out.add(new ArrayList<Integer>(list){{add(target);}});
return;
}
// 为什么只要到target/2就好了呢 动脑想一想
for (int i = start; i <= target/2 ; i++) {
list.add(i);
myDfsII(i,target-i,needCount-1,list);
// 这里是关键 要回退到上一个状态
list.pollLast();
}
}
如果有可以继续优化或错误的地方,麻烦告知交流一下