题目实例Ⅰ
784. 字母大小写全排列
给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例 1:
输入:S = “a1b2”
输出:[“a1b2”, “a1B2”, “A1b2”, “A1B2”]
示例 2:
输入:S = “3z4”
输出:[“3z4”, “3Z4”]
示例 3:
输入:S = “12345”
输出:[“12345”]
提示:
友情链接:https://leetcode-cn.com/problems/letter-case-permutation/
代码实战Ⅰ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| class Solution { StringBuilder path = new StringBuilder(); public List<String> letterCasePermutation(String s) { ArrayList<String> res = new ArrayList<>(); backTracking(s, res, 0); return res; }
public void backTracking(String s, ArrayList<String> res, int index) { if (path.length() == s.length()) { res.add(new String(path.toString())); return; }
for (int i = index; i < s.length(); i++) { char ch = s.charAt(i); if (Character.isDigit(ch)) { path.append(ch); backTracking(s, res, i + 1); path.deleteCharAt(path.length() - 1); } else { path.append(Character.toLowerCase(ch)); backTracking(s, res, i + 1); path.deleteCharAt(path.length() - 1);
path.append(Character.toUpperCase(ch)); backTracking(s, res, i + 1); path.deleteCharAt(path.length() - 1); } } } }
|
题目实例Ⅱ
47. 全排列 II
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例 2:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
提示:
- 1 <= nums.length <= 8
- -10 <= nums[i] <= 10
友情链接:https://leetcode-cn.com/problems/permutations-ii/
代码实战Ⅱ
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> res = new ArrayList<>(); LinkedList<Integer> path = new LinkedList<>(); int depth = 0; Arrays.sort(nums); boolean[] used = new boolean[nums.length]; backTracking(nums, used, path, depth, res); return res; }
public static void backTracking(int[] nums, boolean[] used, LinkedList<Integer> path, int depth, List<List<Integer>> res) { if (nums.length == depth) { res.add(new ArrayList<>(path)); return; } for (int i = 0; i < nums.length; i++) { if (!used[i]) { if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) { continue; } path.add(nums[i]); used[i] = true; backTracking(nums, used, path, depth + 1, res); used[i] = false; path.removeLast(); } } } }
|