如何在 C 或 Objective C 中进行 n 嵌套 for 循环
如何做这样的事情
for(int a = 0; a<2; a++){
for(int b = 0; b<2; b++){
for(int c = 0; c<2; c++){
for(int d = 0; d<2; d++){
n[a+b+c+d]=x[a]*y[b]*z[c]...
}}}}
但我有 x [n]...
How to do something like this
for(int a = 0; a<2; a++){
for(int b = 0; b<2; b++){
for(int c = 0; c<2; c++){
for(int d = 0; d<2; d++){
n[a+b+c+d]=x[a]*y[b]*z[c]...
}}}}
But i have x [n]...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
递归:
要启动递归,请从
do_sum(n, x, max_n, 0, 0)
开始Recursively:
To initiate the recursion, start with
do_sum(n, x, max_n, 0, 0)
@jbx 是对的:递归是可行的方法。假设
n[]
和x[]
是全局变量:@jbx is right: recursively is the way to go. Assuming
n[]
andx[]
are globals:实际上,每个维度的深度仅为 2,即 2 * N 总可能性。
奇怪的是,它将访问 n[] 中的相同元素以获得不同的值,从而覆盖一些内容:
a = 0、b = 1、c = 0、d = 1
a = 1、b = 1、c = 0、d = 0
...
n[a + b + c + d] 实际上只是为 C(4,2) 等索引到 n[2] 中。
我认为实际的问题应该被标记并重新思考。
这似乎不是一个经过深思熟虑的问题。
但如果有的话 - 我会使用回溯(递归)方法,如果这确实是用户想要的。 (特别是如果有 N 维 - 因为没有真正好的方法来迭代执行此操作,除非您想对此应用 dp,这可能超出了最终用户的能力)
Actually the depth for these is just 2 for each dimension., i.e., 2 * N total posibilities.
Something that is weird that is it will access the same element in n[] for different values, overwriting things:
a = 0, b = 1, c = 0, d = 1
a = 1 , b = 1, c = 0, d = 0
...
n[a + b + c + d] is actually just indexing into n[2] for C(4,2) etc.
I think the actual question should be flagged and re-thought.
This doesn't seem like a well-thought question.
But if anything - I would go with the backtracking (recursion) method, if that's really what the user wants. (especially if there's N dimensions - as there's no real great way of doing this thing iteratively, unless you want to apply dp on this, which is probably over the head of the end user)