LeetCode216 组合总和 III
题目:
找出所有相加之和为 n 的 k 个数的组合,且满足下列条件:
只使用数字1到9
每个数字 最多使用一次
返回 所有可能的有效组合的列表 。该列表不能包含相同的组合两次,组合可以以任何顺序返回。
示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]
解释:
1 + 2 + 4 = 7
没有其他符合的组合了。
示例 2:
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
解释:
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
没有其他符合的组合了。
示例 3:
输入: k = 4, n = 1
输出: []
解释: 不存在有效的组合。
在[1,9]范围内使用4个不同的数字,我们可以得到的最小和是1+2+3+4 = 10,因为10 > 1,没有有效的组合。
思路:
代码:
public class Solution {
IList<IList<int>> res = new List<IList<int>>();
IList<int> list = new List<int>();
public IList<IList<int>> CombinationSum3(int k, int n)
{
BackTracking(k, n, 1, 0);
return res;
}
public void BackTracking(int k, int targetSum, int startIndex, int sum)
{
//剪枝
if (sum > targetSum) return;
if (list.Count == k)
{
if (sum == targetSum)
{
res.Add(new List<int>(list));
}
return;
}
for (int i = startIndex; i <= 9; i++)
{
sum += i;
list.Add(i);
BackTracking(k, targetSum, i + 1, sum);
//回溯(最关键的一步)
sum -= i;
list.RemoveAt(list.Count - 1);
}
}
}
LeetCode17 电话号码的字母组合
题目:
给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。
给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。
示例 1:
输入:digits = “23”
输出:[“ad”,“ae”,“af”,“bd”,“be”,“bf”,“cd”,“ce”,“cf”]
示例 2:
输入:digits = “”
输出:[]
示例 3:
输入:digits = “2”
输出:[“a”,“b”,“c”]
代码:
public class Solution {
IList<string> res1 = new List<string>();
public IList<string> LetterCombinations(string digits)
{
Dictionary<char, string> dic = new Dictionary<char, string>();
if (digits.Length == 0) return res1;
dic.Add('2', "abc");
dic.Add('3', "def");
dic.Add('4', "ghi");
dic.Add('5', "jkl");
dic.Add('6', "mno");
dic.Add('7', "pqrs");
dic.Add('8', "tuv");
dic.Add('9', "wxyz");
BackTracking1(0, "", digits, dic);
return res1;
}
public void BackTracking1(int startIndex, string str, string digits, Dictionary<char,string> dic)
{
if (str.Length == digits.Length)
{
res1.Add(str);
return;
}
string temp = dic[digits[startIndex]];
for (int i = 0; i < temp.Length; i++)
{
str += temp[i];
BackTracking1(startIndex + 1, str, digits, dic);
str = str.Remove(str.Length - 1);
}
}
}