zoukankan      html  css  js  c++  java
  • 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)

    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;
      }
    }
  • 相关阅读:
    常见的行元素与块元素
    [转]SVN服务器部署并实现双机同步及禁止普通用户删除文件
    [转]Axure共享工程Shared Project(二):编辑修改和提交
    如何添加网络打印机
    [转]JSON 转换异常 死循环 There is a cycle in the hierarchy
    比较常用的Properties配置文件的使用方法示例
    解决Tomcat项目重复加载导致pemgen space内存溢出
    怎样批量删除.svn文件
    [转]前端工程师必须掌握的知识点
    Freemarker 使用
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10291879.html
Copyright © 2011-2022 走看看