递归调用握手派对

huangapple go评论93阅读模式
英文:

Recursive call for handshaking party

问题

目前,我正在进行递归赋值,我需要计算夫妻之间的握手次数。在这个由 N 对夫妻组成的聚会中,只有一种性别(男性或女性)可以与每个人都握手。一个示例如下:
递归调用握手派对

这是我目前的递归方法,我在这里遇到了困难,你们能帮我解决一下吗?

public int solve(int n){
    if(n==1){
        return 0;
    } else{
        return ((n*2)-2)+solve(n-1);
    }
}

(注意:此处是您提供的代码,已翻译。)

英文:

currently, I'm doing a recursive assignment, where I need to count the number of handshakes between couples. In this party of N couples, only one gender (either male or female) can initiate shake hands with everyone. An example is like this:
递归调用握手派对

This is my method of recursive so far and I'm really stuck here, can you guys help me with this

public int solve(int n){
		if(n==1){
			return 0;
		} else{
			return ((n*2)-2)+solve(n-1);
		}
	}

答案1

得分: 1

我将按照图表的指示,并假设女性是发起握手的一方。

假设我们有N对夫妇:

第一对夫妇中的女性将与每个其他女性握手,总共握手次数为N-1次。
第一对夫妇中的女性将与除了她自己的伴侣之外的每个男性握手,总共握手次数为N-1次。
第一对夫妇中的男性将与每个其他女性握手,总共握手次数为N-1次。
第一对夫妇中的男性将不会与任何其他男性握手,因为他们不能发起握手。

因此,第一对夫妇贡献的握手总数为3(N-1)次。
然后您可以在下一对夫妇上进行递归,将N-1作为参数传入,因为第一对夫妇的握手已经被计算在内。
依此类推。

最终结果为:

public int solve(int n){
   if(n <= 1) return 0;
   return 3 * (n - 1) + solve(n-1);
}
英文:

I will follow the diagram and assume that the women are the ones initiating handshakes.

Say we have N couples:

The female from the 1st couple will shake hands with every other female, resulting in N-1 shakes.
The female from the 1st couple will shake hands with every male that is not her own partner, resulting in N-1 shakes.
The male from the 1st couple will shake hands with every other female, resulting in N-1 shakes.
The male from the 1st couple will NOT shake hands with any of the males, since they cannot initiate handshakes.

So the total number of shakes that the first couple contributes is 3(N-1).
Then you can recurse on the next couple, passing in N-1 as the parameter, since the 1st couple's handshakes have already been counted.
And so on.

Resulting in:

public int solve(int n){
   if(n &lt;= 1) return 0;
   return 3 * (n - 1) + solve(n-1);
}

huangapple
  • 本文由 发表于 2020年10月15日 09:03:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/64363448.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定