216. 组合总和 III?
? public List<List<Integer>> combinationSum3(int k, int n) { List<Set<Integer>> res = new ArrayList<>(); Set<Integer> path = new HashSet<>(); countNum(k, n, path, res); List<List<Integer>> result = new ArrayList<>(); for (Set<Integer> re : res) { result.add(re.stream().collect(Collectors.toList())); } return result; // HashSet<List<Integer>> lists = new HashSet<>(result); // return lists.stream().collect(Collectors.toList()); } public void countNum(int k, int n, Set<Integer> path, List<Set<Integer>> res) { if (path.size() > k || sumNum(path) > n) { return; } if (path.size() == k && sumNum(path) == n&&!res.contains(path)) { res.add(new HashSet<>(path)); return; } for (int i = 1; i < 10; i++) { if (!path.contains(i)) { path.add(i); countNum(k, n, path, res); path.remove(i); } } } public int sumNum(Set<Integer> path) { int sum = 0; for (Integer integer : path) { sum += integer; } return sum; }
17. 电话号码的字母组合
public List<String> letterCombinations(String A) { if (A == null || A.length() == 0) { return new ArrayList<>(); } StringBuffer box = new StringBuffer(); List<String> ans = new ArrayList<>(); backtrace(A, 0, box, ans); return ans; } final String[] ds = new String[] { "","", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" }; void backtrace(String A, int i, StringBuffer box, List<String> ans) { final int N = A == null ? 0 : A.length(); // 如果我们发现状态满足要求 if (box.length() == N) { ans.add(box.toString()); } // 如果发现越界,第N个人开始就没有宝石选项了 if (i >= N) { return; } // 遍历第i个人可以选择的宝石 final int stonelndex = (int) (A.charAt(i) - '0'); for (int idx = 0; idx < ds[stonelndex].length(); idx++) { // 拿到宝石 Character stone = ds[stonelndex].charAt(idx); // /放到箱子中 box.append(stone); backtrace(A, i + 1, box, ans); // 把自己的宝石拿出来,然后保持箱子原样! box.deleteCharAt(box.length() - 1); } }