题解 | #全排列#

全排列

https://www.nowcoder.com/practice/5632c23d0d654aecbc9315d1720421c1

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\n");
        while (scanner.hasNext()) {
            ArrayList<String> arrayList = new ArrayList<>();
            String S = scanner.next();
            dfs(0, S.toCharArray(), arrayList);
            Collections.sort(arrayList);
            arrayList.forEach(System.out::println);
        }
    }

    public static void dfs(int i, char[] nums, ArrayList<String> list) {
        if (i == nums.length) {
            String s = Arrays.toString(nums);
            String replace = s.replace("[", "").replace("]", "").replaceAll(" ",
                             "").replaceAll(",", "");
            list.add(replace);
            return;
        }
        boolean[] visited = new boolean[10];
        for (int j = i; j < nums.length; j++) {
            if (!visited[nums[j] - 'a']) {
                visited[nums[j] - 'a'] = true;
                swap2(nums, i, j);
                dfs(i + 1, nums, list);
                swap2(nums, i, j);
            }
        }
    }

    public static void swap2(char[] nums, int i, int j) {
        char T = nums[i];
        nums[i] = nums[j];
        nums[j] = T;
    }
}

全部评论

相关推荐

07-10 14:08
已编辑
江西农业大学 Java
念旧select:做完把项目放到自己硬盘里给他看,看完拷走
点赞 评论 收藏
分享
07-11 13:16
湖南工学院 Java
坚定的芭乐反对画饼_...:谁也不知道,毕竟现在的互联网和十年前已经完全不同了,谁都无法预测未来
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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