All Permutations I - Medium

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)

public class Solution {
  public List<String> permutations(String set) {
    // Write your solution here
    List<String> res = new ArrayList<>();
    if(set == null || set.length() == 0) {
      return res;
    }
    char[] chs = set.toCharArray();
    boolean[] visited = new boolean[chs.length];
    dfs(chs, visited, new StringBuilder(), res);
    return res;
  }
  
  private void dfs(char[] chs, boolean[] visited, StringBuilder sb, List<String> res) {
    if(sb.length() == chs.length) {
      res.add(sb.toString());
      return;
    }
    for(int i = 0; i < chs.length; i++) {
      if(!visited[i]) {
        sb.append(chs[i]);
        visited[i] = true;
        dfs(chs, visited, sb, res);
        sb.deleteCharAt(sb.length() - 1);
        visited[i] = false;
      }
    }
  }
}

 

 

改进:用swap,in-place操作,不需要StringBuilder

string长度为n,recursion level = n,第一层考虑位置0,将它和0,1,2,3,...n-1分别交换,有n种排法;第二层考虑位置1,10交换在第一层已经考虑过了,需要和剩下的1,2,3,4,...n-1交换,有n-1种排法;...;最后一层考虑位置n-1,只有一种排法,即和自身交换

time: O(n!), space: O(n)

public class Solution {
  public List<String> permutations(String set) {
    // Write your solution here
    List<String> res = new ArrayList<>();
    if(set == null || set.length() == 0) {
      return res;
    }
    char[] chs = set.toCharArray();
    dfs(chs, 0, res);
    return res;
  }
  
  private void dfs(char[] chs, int index, List<String> res) {
    if(index == chs.length) {
      res.add(new String(chs));
      return;
    }
    for(int i = index; i < chs.length; i++) {
      swap(chs, index, i);
      dfs(chs, index + 1, res);
      swap(chs, index, i);
    }
  }
  
  private void swap(char[] arr, int i, int j) {
    char tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
  }
}

 

posted @ 2019-01-19 15:29  fatttcat  阅读(209)  评论(0编辑  收藏  举报