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

 

转载于:https://www.cnblogs.com/fatttcat/p/10291879.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值