题解 | #字符串的排列#
字符串的排列
https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7
import java.util.*; import java.io.*; public class Solution { public ArrayList<String> Permutation(String str) { if (str == null) return null; char[] nums = str.toCharArray(); ArrayList<String> list = new ArrayList<>(); if (nums.length == 0) return list; dfs(0, nums, list); return list; } private void dfs(int idx, char[] nums, ArrayList<String> list) { // 不能再往下搜索 if (idx == nums.length) { StringBuilder result = new StringBuilder(); for (char value : nums) { result.append(value); } list.add(result.toString()); return; } // 枚举这一层所有可以做出的选择 Set<Character> set = new HashSet(); for (int i = idx; i < nums.length; i++) { if(set.contains(nums[i])){ continue; } set.add(nums[i]); swap(nums, idx, i); dfs(idx + 1, nums, list); swap(nums, idx, i); } } private void swap(char[] nums, int i, int j) { char tmp = nums[i]; nums[i] = nums[j]; nums[j] = tmp; } }
解题思想:DFS标准模块,主要是 枚举这一层所有可以做出的选择
#算法##算法笔记#