46. 全排列
class Solution {
public List< List< Integer> > permute ( int [ ] nums) {
List< List< Integer> > res = new ArrayList < > ( ) ;
int len = nums. length;
if ( len == 0 ) return res;
boolean [ ] used = new boolean [ len] ;
Deque< Integer> path = new ArrayDeque < > ( ) ;
dfs ( nums, 0 , path, res, used) ;
return res;
}
public void dfs ( int [ ] nums, int depth,
Deque< Integer> path, List< List< Integer> > res, boolean [ ] used) {
if ( nums. length == depth) {
res. add ( new ArrayList < > ( path) ) ;
return ;
}
for ( int i = 0 ; i < nums. length; i++ ) {
if ( ! used[ i] ) {
path. addLast ( nums[ i] ) ;
used[ i] = true ;
dfs ( nums, depth + 1 , path, res, used) ;
used[ i] = false ;
path. removeLast ( ) ;
}
}
}
}
47. 全排列 II
class Solution {
public List< List< Integer> > permuteUnique ( int [ ] nums) {
List< List< Integer> > res = new ArrayList < > ( ) ;
int len = nums. length;
if ( len == 0 ) return res;
boolean [ ] used = new boolean [ len] ;
Deque< Integer> path = new ArrayDeque < > ( ) ;
Arrays. sort ( nums) ;
dfs ( nums, 0 , path, res, used) ;
return res;
}
public void dfs ( int [ ] nums, int depth,
Deque< Integer> path, List< List< Integer> > res, boolean [ ] used) {
if ( nums. length == depth) {
res. add ( new ArrayList < > ( path) ) ;
return ;
}
for ( int i = 0 ; i < nums. length; i++ ) {
if ( used[ i] ) continue ;
if ( i > 0 && nums[ i] == nums[ i- 1 ] && used[ i- 1 ] == false )
continue ;
path. addLast ( nums[ i] ) ;
used[ i] = true ;
dfs ( nums, depth + 1 , path, res, used) ;
used[ i] = false ;
path. removeLast ( ) ;
}
}
}
剑指 Offer 38. 字符串的排列
class Solution {
public String[ ] permutation ( String s) {
List< String> res = new ArrayList < > ( ) ;
char [ ] arr = s. toCharArray ( ) ;
Arrays. sort ( arr) ;
StringBuilder sb = new StringBuilder ( ) ;
boolean [ ] used = new boolean [ arr. length] ;
dfs ( arr, 0 , res, sb, used) ;
return res. toArray ( new String [ res. size ( ) ] ) ;
}
public void dfs ( char [ ] arr, int path, List< String> res, StringBuilder sb, boolean [ ] used) {
if ( path == arr. length) {
res. add ( sb. toString ( ) ) ;
return ;
}
for ( int i = 0 ; i < arr. length; i++ ) {
if ( used[ i] ) continue ;
if ( i > 0 && arr[ i] == arr[ i- 1 ] && ! used[ i - 1 ] )
continue ;
sb. append ( arr[ i] ) ;
used[ i] = true ;
dfs ( arr, path + 1 , res, sb, used) ;
used[ i] = false ;
sb. deleteCharAt ( sb. length ( ) - 1 ) ;
}
}
}