题解 | #全排列#

全排列

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;
    }
}

全部评论

相关推荐

03-25 19:00
东北大学 Java
程序员牛肉:太好了,是聊天记录。不得不信了。 当个乐子看就好,不要散播焦虑
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务