当前位置:网站首页>发邮件:错排问题的分析
发邮件:错排问题的分析
2022-06-09 12:40:00 【little-peter】
提出问题:有一天,有五个人各自收到了一封信,每个人的家门前都有一个自己的信箱,可是送信员在送信的时候恰好把每个人的信都送到了别人家的信箱里,问:满足这样送信方案数共有多少种?
- 分析问题
当n个编号元素放在n个编号位置,错排的方法数记着D(n)~
⒈把第n个元素放在一个位置,比如位置k,一共有(n-1)种方法;
⒉放编号为k的元素,这时有两种情况:
1°把它放到位置n,那么,对于剩下的(n-1)个元素,由于第k个元素放到了位置n,剩下(n-2)个元素就有D(n-2)种方法;
2°第k个元素不把它放到位置n,这时,对于这(n-1)个元素,有D(n-1)种方法;.
于是有:
D(n) = (n-1) [D(n-2) + D(n-1)]
- 解决问题

我们以发邮件这个相同的问题来举例,根据以上分析,我们可得到以下代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
long sum = count(n);
System.out.println(sum);
}
}
//计算所有人都收不到自己的邮件的情况情况:错排算法
private static long count(int n) {
if (n == 1) {
return 0;
} else if (n == 2) {
return 1;
} else {
return (n - 1) * (count(n - 1) + count(n - 2));
}
}
}
边栏推荐
- 6000 字+,帮你搞懂互联网架构演变历程!
- Digital transformation: how to gain organizational recognition?
- 2022.5.23-----leetcode.675
- go语言搬砖之gojmespath实现查询json数据
- 面试题 08.08. 有重复字符串的排列组合
- 互联网拓扑是怎样构成的?又代表了什么?
- [Clickhouse column] installation and verification of stand-alone version
- 云呐|服务器监控的重要性,监控管理服务器有什么作用
- 对某快捷酒店一次内网测试
- [leetcode weekly race record] record of the 79th biweekly race + the 295th weekly race
猜你喜欢

Yunna | how to do a good inventory of fixed assets? How to count fixed assets

Digital transformation: how to gain organizational recognition?

Yunna intelligent operation and maintenance management system platform, visual operation and maintenance system management

云呐|数据库监控一般监控什么

Jstat details

6000 + words to help you understand the evolution of Internet architecture!

【clickhouse专栏】单机版的安装与验证

未磁科技完成超亿元A轮融资,核心团队毕业于北航

top命令的详解

“地球外存在生命之源”上热搜,外星发现氨基酸到底有什么用?
随机推荐
6000 字+,帮你搞懂互联网架构演变历程!
2022.5.26-----leetcode.699
mysql中的delete,drop和truncate有什么区别
Using kubekey to build kubernetes/kubesphere environment
不看全图看局部,CNN性能竟然更强了
Hype plagiarism, insider fraud common NFT scams and security suggestions on opensea
[signalr complete series] Realization of signalr real-time communication in net core
5G發牌三周年 雲網融合加速 如何解决企業網絡之憂?
DDD建模方法论之【事件风暴法】
Implementation of querying JSON data with gojmespath in go language
VMware ESXI software 英文版安装步骤
云呐|固定资产如何管理比较好?公司固定资产怎么管理?
[Clickhouse column] installation and verification of stand-alone version
Explain the three ways to remove duplicate data in MySQL
What is the seven layer network structure for? Just read this article
Wsl2 environment setup
云呐|资产管理系统有哪些类型,分为哪几方面
leetcode:497. 非重叠矩形中的随机点【随缘随机 + 前缀和二分 + 过了就行】
Database installation --mysql
面试题 05.04. 下一个数