在Facebook求职面试能力测试中提出了以下问题:
A permutation is a list of K numbers, each between 1 and K (both inclusive),
that has no duplicate elements.
Permutation X is lexicographically smaller than Permutation Y iff for some
i <= K:
All of the first i-1 elements of X are equal to first i-1 elements of Y.
ith element of X is smaller than ith element of Y.
You are given a permutation P, you can exchange some of its elements as many
times as you want in any order. You have to find the lexicographically smallest
Permutation that you can obtain from P.
K is less than 101.
Input Format:
First line of input contains K being the size of permutation.
Next line contains K single spaced numbers indicating the permutation.
Each of next K lines contains K characters, character j of line i is equal to
'Y' if you can exchange ith and jth element of a permutation, and
'N' otherwise.
Output Format:
Print K numbers with a space separating each of them indicating the
permutation.
Sample Input
3
3 1 2
NNY
NNN
YNN
Sample Output
2 1 3
Sample Input
3
3 2 1
NYN
YNY
NYN
Sample Output
1 2 3
In the first example you can exchange first element with last element to
obtain 2 1 3 from 3 1 2.
我做了什么?
我首先生成了所有排列。
然后,我丢弃了那些不可行的排列。在示例 1 中:1 3 3
不可行,因为位置 1 和 2 是不可交换的。
从所有允许的排列列表中,我选择了字典顺序最小的一个作为解决方案。
上述解决方案的问题:
我的解决方案非常适用于K<=25
. 当 K 的大小变得大于 25 时,解决方案真的很慢。因为K=100
,我什至没有得到输出60 minutes
。
我的问题是:
我应该如何优化我的解决方案?
可以在不产生所有排列的情况下完成吗?
带有解释和伪代码(或代码)的更好解决方案将非常有帮助。
谢谢!