我需要一些帮助来将迭代算法转换为递回算法。
我需要生成总和为 11 的所有 4 个数字,其中第一个数字始终为 1,其他 3 个数字至少为 2。
for(int i = 1 ; i < 7; i ){
for(int j = 2; j < 7; j ){
for(int k = 2; k < 7; k ){
for(int p = 2; p < 7; p ){
if(i j k p == 11 && i == 1){
printf(" %d %d %d %d \n", i, k, j, p);
}
}
}
}
}
一些输出示例:
1 2 2 6
1 3 2 5
1 4 2 4
1 5 2 3
这会起作用,但它的设计很糟糕,我需要用递回来做。
uj5u.com热心网友回复:
第一个数字总是 1,你不需要回圈。对于其余部分,您可以创建一个函式,将所有可能性求和为特定数字。这是一个 Java 语法的程序,但不使用类,因此很容易翻译成 C:
public void printPossibilities(int rest, int[] buffer, int len, int total) {
if (len 1 == total) {
buffer[len] = rest;
System.out.println(Arrays.toString(buffer));
} else {
// check if it is possible that the rest of the numbers are >= 2
for (int i = 2; rest >= i (total - len - 1) * 2; i ) {
buffer[len] = i;
printPossibilities(rest - i, buffer, len 1, total);
}
}
}
// call with
int[] buffer = new int[4];
buffer[0] = 1;
printPossibilities(10, buffer, 1, 4);
uj5u.com热心网友回复:
首先,这里有点数学:假设有 4 个数字,num1,num2,num3 和 num4,它们需要相加为 11。所以,
num1 num2 num3 num4=11
num1=1 and num2>=2, num3>=2, num4>=2
num2 num3 num4=11-num1=10
(num2-2) (num3-2) (num4-2)=10-(2 2 2)=4
var2 var3 var4=4, where var2, var3 and var4>=0
归结为以递回方式找到3个非负数,使它们总和为4。这是一个通用的解决方案,然后可以进行相应的修改:这是一个可以做到这一点的代码,在 C 中:
#include <iostream>
#include <vector>
void get_target_sum(std::vector<std::vector<int>>& total_ans, std::vector<int>& curr_ans, int num_remaining, int targetnum){
// total_ans denotes all the tuples, curr_ans denotes the current
// computation, num_remaining denotes the numbers remaining which
// should sum up to targetnum.
// each time we find a valid number which can be a part of our answer, we
// add it to curr_ans, decrement num_remaining since the numbers remaining
// has decreased by 1, and decrease the target number to be found by the
// value of the number
if(num_remaining<1){return;}
if(num_remaining==1){
curr_ans.push_back(targetnum);
total_ans.push_back(curr_ans);
curr_ans.pop_back();
}
for(int curr_num=0;curr_num<targetnum;curr_num ){
curr_ans.push_back(curr_num);
get_target_sum(total_ans,curr_ans,num_remaining-1,targetnum-curr_num);
curr_ans.pop_back();
}
}
int main()
{
std::vector<std::vector<int>>final_ans;
std::vector<int> curr_ans;
get_target_sum(final_ans,curr_ans,3,4);
for(int i=0;i<final_ans.size();i ){
std::cout<<1<<" ";
// The first variable
for(auto num:final_ans[i]){
std::cout<<num 2<<" ";
// the other 3 variables, incremented by 2.
}
std::cout<<"\n";
}
return 0;
}
输出:https ://onlinegdb.com/gdQdLgni8
0 评论