题解 | #字符串的排列#

字符串的排列

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


import java.util.ArrayList;
import java.lang.reflect.Array;
import java.util.HashSet;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        HashSet<String> res = new HashSet<>();
        solution(str.toCharArray(), res, "");
        return new ArrayList<String>(res);
    }
    
    
    public void solution(char[] chars, HashSet<String> res, String resStr) {
        if (chars.length == 1) {
            res.add(resStr + chars[0]);
            return;
        }
        for (int i = 0; i < chars.length; i++) {
            char aChar = chars[i];
//            char[] temp = new char[chars.length - 1];
            char[] temp = (char[]) Array.newInstance(chars.getClass().getComponentType(), chars.length - 1);
            // 将第i位截掉
            System.arraycopy(chars, 0, temp, 0, i);
            if (i < chars.length - 1) {
                System.arraycopy(chars, i + 1, temp, i, chars.length - i - 1);
            }
//            temp = ArrayUtil.remove(chars, i);
            solution(temp, res, resStr + aChar);
        }
    }
    
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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