由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - 生成一个有重复数的全排列,怎么做比较好
相关主题
有重复元素的全排列,递归算法抽空简单说一下昨天的Google Phone Interview
关于排列组合的题目的算法用了递归以后,怎么计算空间复杂度?
对自己DFS能力彻底的绝望了。C++ Q96: function inheritance
晕了,有人用iteration解n queens么调试成功的next_permutation代码
Exposed上一道string permutation的题问题:从电话号码打出所有单词
String permunation question (CS)那个24 game given 4 number用= - × /的题
问一个题问一道google的面试题
一个容易记忆的permutation算法wildcard string matching,谁有最简洁的非递归解法?
相关话题的讨论汇总
话题: int话题: used话题: perm话题: 递归
进入JobHunting版参与讨论
1 (共1页)
f**********t
发帖数: 1001
1
想了半天,快疯了…… :(
C***y
发帖数: 2546
2
非递归的参考stl next_permutation
递归的也可以做,不过需要先排序,遇到前后相同的字符,特殊处理一下

【在 f**********t 的大作中提到】
: 想了半天,快疯了…… :(
h**********8
发帖数: 267
3
mark

【在 C***y 的大作中提到】
: 非递归的参考stl next_permutation
: 递归的也可以做,不过需要先排序,遇到前后相同的字符,特殊处理一下

n**z
发帖数: 155
4
mark
f**********t
发帖数: 1001
5
嗯,想了一下。递归的首先要排序,如:1,1,2,2,3.
然后要考虑好两种情况:
1)相同的不swap。如2和2.
2)保证有重复的(如1和2)不会重复出现在开头。例如第一个1出现在开头了,第二个1
出现在开头的情况就略去
n**z
发帖数: 155
6
用一个hashMap 来记住已经排过的组合行不。
这道题有点难Programmer Interview 上的那个递归算法我已经背的很难受了。
i**********e
发帖数: 1145
7
利用 next_permutation 效率要好些。
代码请参考这里:
http://www.mitbbs.com/article0/JobHunting/31891031_0.html
递归的话,循环里跳到下一个不重复的元素。
例如:
[2 2 3]
=> [2 ...] ( [2 2 3] and [2 3 3] )
把重复的 2 跳过
=> [3 ...] ( [3 2 2] )
// precondition: A must be sorted
void printPermutations(int A[], int n, int count, bool used[], int perm[]) {
if (count == n) {
for (int i = 0; i < n; i++)
cout << A[perm[i]] << " ";
cout << endl;
return;
}
for (int i = 0; i < n; i++) {
if (used[i]) continue;
perm[count] = i;
used[i] = true;
printPermutations(A, n, count+1, used, perm);
used[i] = false;
// 跳过重复元素
int curr = A[i];
while (i+1 < n && A[i+1] == curr)
i++;
}
}
void printPermutations(int A[], int n) {
int perm[256];
bool used[256] = { false };
printPermutations(A, n, 0, used, perm);
}
同样的思路可以用于以下的问题,如果需要多练习递归题不妨试试吧:
http://www.ihas1337code.com/2010/09/print-all-combinations-of-n
Find all possible combination of numbers using a pre-defined candidate set.
Each number from the candidate set may be used only once in the combination.
For example,
Candidate Set = {10, 1, 2, 7, 6, 1, 5}
Target Number = 8
One possible output could be:
1+1+6
1+2+5
1+7
2+6
一些常见面试题的答案与总结 -
http://www.ihas1337code.com
f********3
发帖数: 210
8
mark

【在 i**********e 的大作中提到】
: 利用 next_permutation 效率要好些。
: 代码请参考这里:
: http://www.mitbbs.com/article0/JobHunting/31891031_0.html
: 递归的话,循环里跳到下一个不重复的元素。
: 例如:
: [2 2 3]
: => [2 ...] ( [2 2 3] and [2 3 3] )
: 把重复的 2 跳过
: => [3 ...] ( [3 2 2] )
: // precondition: A must be sorted

1 (共1页)
进入JobHunting版参与讨论
相关主题
wildcard string matching,谁有最简洁的非递归解法?Exposed上一道string permutation的题
求G加一题的线性解法String permunation question (CS)
请教下leetcode Permutations II问一个题
wordBreak问题,有非递归的方法么一个容易记忆的permutation算法
有重复元素的全排列,递归算法抽空简单说一下昨天的Google Phone Interview
关于排列组合的题目的算法用了递归以后,怎么计算空间复杂度?
对自己DFS能力彻底的绝望了。C++ Q96: function inheritance
晕了,有人用iteration解n queens么调试成功的next_permutation代码
相关话题的讨论汇总
话题: int话题: used话题: perm话题: 递归