Skip to content

Commit 5afa285

Browse files
committed
permutation
1 parent 1dcf506 commit 5afa285

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

src/Permutations/Solution.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package Permutations;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.stream.Collectors;
6+
import java.util.stream.IntStream;
7+
8+
/**
9+
* User: Danyang
10+
* Date: 1/20/2015
11+
* Time: 11:35
12+
*
13+
* Given a collection of numbers, return all possible permutations.
14+
15+
For example,
16+
[1,2,3] have the following permutations:
17+
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
18+
19+
*/
20+
public class Solution {
21+
public List<List<Integer>> permute(int[] num) {
22+
List<List<Integer>> ret = new ArrayList<>();
23+
dfs(IntStream.of(num).boxed().collect(Collectors.toList()), new ArrayList<>(), ret);
24+
return ret;
25+
}
26+
27+
void dfs(List<Integer> seq, List<Integer> cur, List<List<Integer>> ret) {
28+
if(seq.size()==0)
29+
ret.add(new ArrayList<>(cur));
30+
31+
// list manipulation is verbose
32+
for(int i=0; i<seq.size(); i++) {
33+
List<Integer> next = new ArrayList<>(seq);
34+
int t = next.remove(i);
35+
cur.add(t);
36+
dfs(next, cur, ret);
37+
cur.remove(cur.size()-1);
38+
}
39+
}
40+
41+
public static void main(String[] args) {
42+
List<List<Integer>> ret = new Solution().permute(new int[]{0, 1});
43+
System.out.println(ret);
44+
}
45+
}

src/PermutationsII/Solution.java

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package PermutationsII;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
import java.util.stream.Collectors;
6+
import java.util.stream.IntStream;
7+
8+
/**
9+
* User: Danyang
10+
* Date: 1/22/2015
11+
* Time: 19:59
12+
* Given a collection of numbers that might contain duplicates, return all possible unique permutations.
13+
14+
For example,
15+
[1,1,2] have the following unique permutations:
16+
[1,1,2], [1,2,1], and [2,1,1].
17+
*/
18+
public class Solution {
19+
public List<List<Integer>> permuteUnique(int[] num) {
20+
List<Integer> seq = IntStream.of(num).boxed().sorted().collect(Collectors.toList());
21+
List<List<Integer>> ret = new ArrayList<>();
22+
dfs(seq, new ArrayList<>(), ret);
23+
return ret;
24+
}
25+
26+
void dfs(List<Integer> seq, List<Integer> cur, List<List<Integer>> ret) {
27+
if(seq.size()==0)
28+
ret.add(new ArrayList<>(cur));
29+
30+
for(int i=0; i<seq.size(); i++) {
31+
if(i-1>=0 && seq.get(i-1)==seq.get(i)) // jump
32+
continue;
33+
List<Integer> next = new ArrayList<>(seq);
34+
Integer t = next.remove(i);
35+
cur.add(t);
36+
dfs(next, cur, ret);
37+
cur.remove(cur.size()-1);
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)