Data Structure & Algorithm: Level-1 Problem #57. Factorial and Permutation – 1

In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n:

Factorial

Following table shows the values of fractional 0 to 20, note that the value of 0! is 1:

Factorial and Permutation

In mathematics, a permutation of a set is, loosely speaking, an arrangement of its members into a sequence or linear order, or if the set is already ordered, a rearrangement of its elements. The word “permutation” also refers to the act or process of changing the linear order of an ordered set.

In the popular puzzle Rubik’s cube invented in 1974 by Ernő Rubik, each turn of the puzzle faces creates a permutation of the surface colors.

Note: the Rubik‘s cube image above is coming from the Wikipedia page: https://en.wikipedia.org/wiki/Permutation

In many cases, factorial is related to permutation. For example, given 6 different colors to fill in six boxes. The total number of ways to fill in the boxes is a permutation problem, while the result is a factorial of 6.

Given a word, find out how many different ways are there to order the letters from the word.

Sample Input: database

Sample Output: 6720

There are total of 6720 ways to order the letters in the given word, database.


数据结构和算法:初级练习题 #57. 阶乘和排列(一)


阶乘是基斯顿·卡曼(Christian Kramp,1760~1826)于 1808 年发明的运算符号。一个正整数的阶乘factorial)是所有小于及等于该数的正整数的积,正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!。上文中的图表里列出了从0到20阶乘的结果。

排列(permutation),数学的重要概念之一。有限集的子集按某种条件的序化法排成列、排成一圈、不许重复或许重复等。从n个不同元素中每次取出m(1≤m≤n)个不同元素,排成一列,称为从n个元素中取出m个元素的无重复排列或直线排列,简称排列。从n个不同元素中取出m个不同元素的所有不同排列的个数称为排列种数或称排列数,记为Pnm

Permutation

阶乘和排列密切相关,上面排列数的计算结果就是用阶乘来表示。

给定一个单词,计算这个单词里的字母所有的排列总数,注意单词里可能会出现重复的字母。

输入样例: database

输出样例:6720

输入样例中的database里面八个字母,总共有 6720 种排列方式。


Python Solution

Permutation