LF.64.All Permutations I

Given a string with no duplicate characters, return a list with all permutations of the characters.

Examples

  • Set = “abc”, all permutations are [“abc”, “acb”, “bac”, “bca”, “cab”, “cba”]
  • Set = "", all permutations are [""]
  • Set = null, all permutations are []

time:o(n!) space: o(n)

//no duplicate
public class Solution {
  public List<String> permutations(String set) {
    // Write your solution here.
    List<String> res = new ArrayList<>();
    if (set == null) {
        return res ;
    }
    char[] arraySet = set.toCharArray() ;
    dfs(arraySet, res, 0);
    return res ;
  }
  /*
    1) what does it store on each level?
    three levels. each level represents one position
    2) how many different states should we try to put on this level
    remaining (not yet used) letters
  */
  private void dfs(char[] set, List<String> res , int index){
    //base case: termination
    if (index == set.length) {
        res.add(new String(set));
        return ;
    }
    for (int i = index; i< set.length; i++ ) {
        swap(set, i , index) ;
        //向下走,去swap(1,1) swap(1,2)
        dfs(set, res, index+1) ;
        //吐出来, 这样同一级别的 i++ 才会有作用:
        //swap(0,0)完事去弄 swap(0,3)
        swap(set, i , index) ;
    }
  }

  private void swap(char[] set, int left , int right){
    char temp = set[left];
    set[left] = set[right] ;
    set[right] = temp ;
  }
}

 1 public List<String> permutations_2(String set) {
 2     // Write your solution here.
 3     List<String> res = new ArrayList<>() ;
 4     if (set == null) {
 5         return res ;
 6     }
 7     char[] charSets = set.toCharArray() ;
 8     Set<Character> dic = new HashSet<>();
 9     StringBuilder sol = new StringBuilder();
10     helper(charSets, dic, res, sol) ;
11     return res;
12   }
13   private void helper(char[] charSets, Set<Character> dic, List<String> res, StringBuilder sol){
14     //base case: when reaches the bottom, then put it in the res
15     if (sol.length() == charSets.length) {
16         res.add(new String(sol.toString())) ;
17         return ;
18     }
19     // how many levels:
20     for (int i = 0 ; i < charSets.length; i++) {
21         //corner case: dont repeately add same item
22         if (dic.contains(charSets[i])) {
23             continue;
24         }
25         //one state: repeatedly add another item
26         sol.append(charSets[i]);
27         dic.add(charSets[i]);
28         helper(charSets, dic, res, sol) ;
29         //remove
30         sol.deleteCharAt(sol.length()-1) ;
31         dic.remove(charSets[i]);
32     }
33   }
原文地址:https://www.cnblogs.com/davidnyc/p/8689876.html