假设 n = 4
。使用递归,我想返回:
1 1 1 1
1 1 2
1 3
2 1 1
2 2
3 1
4
基本上,我想采用数字
n
并通过组合数字1,2,3和4创建所有可能的变化,当sum == n
时需要这些变化。这是我的第一个想法,但它给了我以下错误信息:
线程“main”中的异常java.lang.StackOverflowError
public static void test_2(String path, int sum, int n){
if(sum == n){
System.out.println(path);
} else {
test_2(path+"1 ", sum + 1, n);
test_2(path+"2 ", sum + 2, n);
test_2(path+"3 ", sum + 1, n);
test_2(path+"4 ", sum + 2, n);
}
}
1 2 1
怎么样?你不想要它,还是只是忘了它? - RaminS