回溯法(Java)

字符串的排列

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

思路:
回溯法 + set去重 + 集合排序

import java.util.*;

public class Solution {

    public ArrayList<String> Permutation(String str) {
        Set<String> list = new HashSet<>();
        backtrace(list,new StringBuilder(str),0);
        ArrayList result = new ArrayList<>(list);
        Collections.sort(result);
        return result;
    }



    public void backtrace(Set list,StringBuilder str,int index){
        if(index + 1 == str.length()){
            list.add(str.toString());
        }else{
            for(int i = index;i < str.length();i++){
                char temp = str.charAt(index);
                str.setCharAt(index,str.charAt(i));
                str.setCharAt(i,temp);
                backtrace(list,str,index + 1);
                temp = str.charAt(index);
                str.setCharAt(index,str.charAt(i));
                str.setCharAt(i,temp);
            }
        }
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
02-14 11:10
点赞 评论 收藏
分享
只写bug的程序媛:才15,我招行20多万,建设银行50多万,说放弃就放弃
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务