码迷,mamicode.com
首页 > 其他好文 > 详细

All Permutations I - Medium

时间:2019-01-19 16:25:31      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:ons   bsp   delete   index   examples   ati   改进   rac   lis   

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;
  }
}

 

All Permutations I - Medium

标签:ons   bsp   delete   index   examples   ati   改进   rac   lis   

原文地址:https://www.cnblogs.com/fatttcat/p/10291879.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!