找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
- 所有数字都是正整数。
- 解集不能包含重复的组合。
示例 1: 输入: k = 3, n = 7 输出: [[1,2,4]]
示例 2: 输入: k = 3, n = 9 输出: [[1,2,6], [1,3,5], [2,3,4]
每次取或者不去i从1-9的数字
class Solution { public List<List<Integer>> combinationSum3(int k, int n) { List<List<Integer>> res = new ArrayList<>(); helper(res, new ArrayList<>(),k,n,1); return res; } private void helper(List<List<Integer>> res, List<Integer> cur, int k, int n, int index) { if (cur.size() == k && n == 0) { res.add(new ArrayList<>(cur)); return; } if (n < 0 || k < cur.size()) return; for (int i = index; i <= 9; i++) { cur.add(i); helper(res, cur,k,n-i,i + 1); cur.remove(cur.size() - 1); } } }
给定一个仅包含数字 2-9
的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
class Solution { public List<String> letterCombinations(String digits) { List<String> res= new ArrayList<>(); String[] phones = {"","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; if (digits == null || digits.length() == 0) return res; dfs(res, phones, digits, 0, ""); return res; } private void dfs(List<String> res, String[] phones, String digits, int index, String s) { if (index == digits.length()) { res.add(s); return; } int idx = digits.charAt(index) - '0'; for (char c : phones[idx].toCharArray()) { dfs(res, phones, digits, index + 1, s + c); } } }
标签:216,digits,return,index,int,res,随想录,字母组合,List From: https://www.cnblogs.com/libertylhy/p/17254479.html