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

77. 组合

回溯三部曲

    1. 确定回溯函数的返回值和参数
       本题中返回结果为一个List,回溯函数肯定不能返回List,返回值为void即可
         参数为n和k
    2. 确定递归中止条件
       找到k个数字的集合就中止本次回溯
    3. 确定单层递归操作
         每层递归函数内,从当前位置向后遍历数字,将数字加入过程集合,进入下一层,之后回溯

class Solution {
	List<Integer> item = new ArrayList<>();
	List<List<Integer>> res = new ArrayList<>();
    public List<List<Integer>> combine(int n, int k) {
		backtracking(n,k,1);
		return res;
    }

	private void backtracking(int n, int k, int nowNum){
		//确定递归中止条件
		//if(nowNum > n){
		//	return;
		//}
		if(item.size() == k){
			res.add(new ArrayList<>(item));
			return;
		}
		for(int i = nowNum; i <= n - (k - item.size()) + 1; i++){
			item.add(i);
			backtracking(n, k, i + 1);
			item.remove(item.size() - 1);
		}

	}
}

——————————————————————————————————————————

216. 组合总和 III 

   回溯三部曲
    1.确定回溯函数返回值和参数
        返回值为void,参数为k,n,和当前开始遍历的数字(1-9)
    2.确定回溯终止条件
        当相加的数字个数等于k时,中止此次回溯。
    3.确定回溯单层过程
        当找到相加之和为 n 的 k 个数时,将此次集合加到res中 

class Solution {
	List<List<Integer>> res = new ArrayList<>();
	List<Integer> item = new ArrayList<>();
	int sum = 0;
    public List<List<Integer>> combinationSum3(int k, int n) {
		backtracking(k, n, 1);
		return res;
    }

	private void backtracking(int k, int n, int startNum){
		if(sum > n){
			return;
		}
		if(item.size() == k){
			if(sum == n){
				res.add(new ArrayList<>(item));
			}
			return;
		}

		for (int i = startNum; i <= 9; i++) {
			item.add(i);
			sum += i;
			backtracking(k, n, i + 1);
			item.remove(item.size() - 1);
			sum -= i;
		}
	}

}

——————————————————————————————————————————

17. 电话号码的字母组合 

 

回溯三部曲
    1.确定回溯函数返回值和参数
        返回值为void,参数为输入字符串digits,以及当前要搜寻的数字位置
    2.确定回溯终止条件
        当当前组合字符串的长度等于digits长度时,将该组合加入返回集合
    3.确定回溯单层过程
        遍历当前数字的所有可用字母,加入组合字符串,回溯后减去当前字母

class Solution {
	char[][] numChars = {
			{'a','b','c'},
			{'d','e','f'},
			{'g','h','i'},
			{'j','k','l'},
			{'m','n','o'},
			{'p','q','r','s'},
			{'t','u','v'},
			{'w','x','y','z'}
	};
	List<String> res = new ArrayList<>();
	StringBuilder str = new StringBuilder();
    public List<String> letterCombinations(String digits) {
		backtracking(digits, 0);
		return res;
    }

	private void backtracking(String digits, int index) {
		if(str.length() == digits.length()){
			if(str.length() > 0){
				res.add(str.toString());
			}
			
			return;
		}
		char[] numChar = numChars[digits.charAt(index) - '2'];

		for (char c : numChar) {
			str.append(c);
			backtracking(digits, index + 1);
			str.deleteCharAt(str.length() - 1);
		}


	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值