Question: Generate all permutations of a given string.
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| private List<String> permutations = new ArrayList<String>(); /** * Generate all the permutations and add to array list * * @param in * @param out * @param used * @param len * @param recLen */ void permute( char [] in, char [] out, char [] used, int len, int recLen) { if (recLen==len) { permutations.add(String.valueOf(out)); return ; } for ( int i= 0 ; i<len; i++) { if (used[i]== 1 ) { continue ; } out[recLen]=in[i]; used[i]= 1 ; permute(in, out, used, len, recLen+ 1 ); used[i]= 0 ; } } List<String> permutations(String num) { char [] out = new char [num.length()]; char [] used = new char [num.length()]; permute(num.toCharArray(), out, used, num.length(), 0 ); return permutations; } |
No comments:
Post a Comment