77. 组合
题目:77. 组合 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
去取值的思路很像之前做过的n数之和,不同之处在于本题组合元素的数量为k,不确定,只能使用递归
solution
public class Solution {
List<IList<int>> results = new List<IList<int>>();
public IList<IList<int>> Combine(int n, int k) {
List<int> result = new List<int>();
combineTraversal(1, n, k, result);
return results;
}
public void combineTraversal(int start, int end, int k, List<int> result)
{
if(start > end) return;
for(int i = start; i <= end; i ++)
{
result.Add(i);
if(result.Count == k) results.Add(new List<int>(result));
else combineTraversal(i + 1, end, k, result);
result.RemoveAt(result.Count - 1);
}
}
}
summary
错误:
将判断列表元素是否完整当作终止条件之一写在了前面,逻辑有些混乱
216. 组合总和 Ⅲ
题目:216. 组合总和 III - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
比上一题多了点条件判断
solution
public class Solution {
List<IList<int>> results = new List<IList<int>>();
public IList<IList<int>> CombinationSum3(int k, int n) {
List<int> result = new List<int>();
combineTraversal(1, k, n, 0, result);
return results;
}
public void combineTraversal(int start, int k, int n, int sum, List<int> result)
{
if(start > 9) return;
if(sum >= n || result.Count >= k) return;
for(int i = start; i <= 9; i ++)
{
result.Add(i);
sum += i;
if(sum == n && result.Count == k) results.Add(new List<int>(result));
else combineTraversal(i + 1, k, n, sum, result);
result.RemoveAt(result.Count - 1);
sum -= i;
}
}
summary
错误:
漏写了sum的回溯
17. 电话号码的字母组合
题目:17. 电话号码的字母组合 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
solution
public class Solution {
public List<string> results = new List<string>();
public List<List<char>> map = new List<List<char>>()
{
new List<char>{},
new List<char>{},
new List<char>{'a', 'b', 'c'},
new List<char>{'d', 'e', 'f'},
new List<char>{'g', 'h', 'i'},
new List<char>{'j', 'k', 'l'},
new List<char>{'m', 'n', 'o'},
new List<char>{'p', 'q', 'r', 's'},
new List<char>{'t', 'u', 'v'},
new List<char>{'w', 'x', 'y', 'z'}
};
public IList<string> LetterCombinations(string digits) {
if (digits == null || digits.Length == 0) return results;
StringBuilder str = new StringBuilder(digits);
StringBuilder result = new StringBuilder();
combineTraversal(str, result, 0);
return results;
}
public void combineTraversal(StringBuilder str, StringBuilder result, int i)
{
List<char> list = map[int.Parse(str[i].ToString())];
foreach(char c in list)
{
result.Append(c);
if(i == str.Length - 1) results.Add(result.ToString());
else combineTraversal(str, result, i + 1);
result.Remove(i, 1);
}
}
}
summary
错误:
1、注意int.Parse方法参数是字符串而非字符。。。
2、这样的写法是错的:
public List<List<char>> map = new List<List<char>>(){
{},
{},
{'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'}
};