Skip to content

Commit 515b41d

Browse files
committed
permutation
1 parent e568389 commit 515b41d

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

common.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,3 +125,41 @@ function countNumber(n){
125125
return count;
126126
}
127127
```
128+
129+
### 8.穷举排列(permutation)
130+
131+
[see](http://www.lifelaf.com/blog/?p=1228)
132+
133+
穷举一个数组中各个元素的排列
134+
135+
策略
136+
137+
减而治之、递归
138+
139+
```js
140+
/**
141+
* Created by cshao on 12/23/14.
142+
*/
143+
144+
function getPermutation(arr) {
145+
if (arr.length == 1) {
146+
return [arr];
147+
}
148+
149+
var permutation = [];
150+
for (var i=0; i<arr.length; i++) {
151+
var firstEle = arr[i];
152+
var arrClone = arr.slice(0);
153+
arrClone.splice(i, 1);
154+
var childPermutation = getPermutation(arrClone);
155+
for (var j=0; j<childPermutation.length; j++) {
156+
childPermutation[j].unshift(firstEle);
157+
}
158+
permutation = permutation.concat(childPermutation);
159+
}
160+
return permutation;
161+
}
162+
163+
var permutation = getPermutation(['a','b','c']);
164+
console.dir(permutation);
165+
```

0 commit comments

Comments
 (0)