字符串的排列

字符串的排列

http://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7

回溯法
调用回溯函数,先判断是否满足结束条件,若满足将其加入序列,return;若不满足使用循环进行回溯。典型的题目有全排列等。
必要的几个参数:
1、标志位数组used[]
2、存储中间结果的容器,如一个String、一个ArrayList等
3、题目中给的已知参数和要返回的结果
代码如下:

import java.util.ArrayList;
import java.util.Collections;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        ArrayList<String> res = new ArrayList<>();
        if(str.length()==0 || str==null){
            return res;
        }
        int used[] = new int[str.length()];
        String temp="";
        backTrack(str,used,temp,res);
        //按字典序
        Collections.sort(res);
        return res;
    }

    public void backTrack(String str,int used[],String temp,ArrayList<String> res){
        if(temp.length()==str.length()){
            res.add(temp);
            return;
        }else{
            for(int i=0;i<str.length();i++){
                if(used[i]==1) continue;
                if(i!=0 && str.charAt(i)==str.charAt(i-1)&& used[i-1]==1) continue;

                temp = temp+str.charAt(i);
                used[i]=1;
                backTrack(str,used,temp,res);

                used[i]=0;
                temp = temp.substring(0,temp.length()-1);
            }
        }

    }
}
全部评论

相关推荐

夏目LTH:这个真的很看运气,多投吧。我从去年十二月底一直投到现在,之前没一个offer,结果两周前投的一家面试官聊的特别好,直接速通offer还给的SP待遇开的比我期望都够。
我的求职进度条
点赞 评论 收藏
分享
找工作勤劳小蜜蜂:矛盾是没有实习,就是没实战经验,公司不想要,公司不要,你就没有实习,你就进入死循环,另外你的项目不是社会现在有大量岗位存在行业用的,云存储人员早就饱和。
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务