就是permutations II考虑有重复字母的情况。
String str = "someString";
char[] charArray = str.toCharArray();
对char array进行排序:
Arrays.sort(charArray)
之后再把CharArray转化成string:
char[] myString = new char[]
{‘T‘, ‘H‘, ‘I‘, ‘S‘, ‘ ‘, ‘I‘, ‘S‘, ‘ ‘, ‘T‘, ‘E‘, ‘S‘, ‘T‘};
String output1 = new String(myString);
permutation II 的代码
public class Solution { public List<List<Integer>> permute(int[] nums) { List<List<Integer>> res = new ArrayList<List<Integer>>(); Arrays.sort(nums); LinkedList<Integer> list = new LinkedList<Integer>(); for (int num : nums) list.add(num); perm(list, 0, res); return res; } private void perm(LinkedList<Integer> nums, int start, List<List<Integer>> res){ if (start == nums.size() - 1){ res.add(new LinkedList<Integer>(nums)); return; } for (int i = start; i < nums.size(); i++){ if (i > start && nums.get(i) == nums.get(i - 1)) continue; nums.add(start, nums.get(i)); nums.remove(i + 1); perm(nums, start + 1, res); nums.add(i + 1, nums.get(start)); nums.remove(start); } } }
时间: 2024-11-08 08:14:11