代码随想录算法训练营第二十五天| 216.组合总和III、17.电话号码的字母组合

216.组合总和III

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

解题思路:依旧是正常遍历,过程中记录遍历的所有节点之和,如果当前元素之和已经大于所给定的值,退回上一节点

java:

class Solution {
    List> result = new ArrayList<>();
	LinkedList path = new LinkedList<>();
	public List> combinationSum3(int k, int n) {
		backTracking(n, k, 1, 0);
		return result;
	}
	private void backTracking(int targetSum, int k, int startIndex, int sum){
		if (sum > targetSum) {
			return;
		}
		if (path.size() == k) {
			if (sum == targetSum) result.add(new ArrayList<>(path));
			return;
		}
		for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) {
			path.add(i);
			sum += i;
			backTracking(targetSum, k, i + 1, sum);
			path.removeLast();
			sum -= i;
		}
	}
}

17.电话号码的字母组合

题目链接:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

解题思路:依旧是组合,重点是拆分字符

java:

class Solution {
    List list = new ArrayList<>();
    public List letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return list;
        }
        String[] numString = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        backTracking(digits, numString, 0);
        return list;
    }
    StringBuilder temp = new StringBuilder();
    public void backTracking(String digits, String[] numString, int num) {
        if (num == digits.length()) {
            list.add(temp.toString());
            return;
        }
        String str = numString[digits.charAt(num) - '0'];
        for (int i = 0; i < str.length(); i++) {
            temp.append(str.charAt(i));
            backTracking(digits, numString, num + 1);
            temp.deleteCharAt(temp.length() - 1);
        }
    }
}

你可能感兴趣的:(算法)