zoukankan      html  css  js  c++  java
  • 面试题:字符串的全排列

    题目描述:输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

    思路:回溯法,求全排列求集合的全部子集

    图片说明

    代码:

    import java.util.List;
    import java.util.Collections;
    import java.util.ArrayList;
    public class Solution {
        public ArrayList<String> Permutation(String str) {
            ArrayList<String> res=new ArrayList<>();
            if (str==null||str.length()==0) return res;
            PermutationHelper(str.toCharArray(),0,res);
            Collections.sort(res);
            return res;
        }
        public void PermutationHelper(char[] cs,int i,ArrayList<String> list){
            if(i==cs.length-1){//不是太懂这一步
                String val=String.valueOf(cs);
                if (!list.contains(val))
                    list.add(val);
            }else{
                for (int j=i;j<cs.length;j++){
                    swap(cs,i,j);
                    PermutationHelper(cs,i+1,list);
                    swap(cs,i,j);
                }
            }
        }
        public void swap(char[] cs,int i,int j){
            char temp =cs[i];
            cs[i]=cs[j];
            cs[j]=temp;
        }
    }
  • 相关阅读:
    IfcSameDirection
    IfcSameCartesianPoint
    java多个文件合并为一个文件
    matlab pan_tompkin算法
    IfcSameAxis2Placement
    IfcOrthogonalComplement
    IfcNormalise
    IfcMakeArrayOfArray
    matlab 日期 年月日时分秒毫秒
    IfcListToArray
  • 原文地址:https://www.cnblogs.com/Aaron12/p/9534764.html
Copyright © 2011-2022 走看看