题目描述:
给定两个整数 n
和 k
,返回范围 [1, n]
中所有可能的 k
个数的组合。
你可以按 任何顺序 返回答案。
思路一:根据起点画二叉树
使用递归的思路:
1)当搜索起点是1,在[2,3,4,....,n]中搜下一个数
2)当搜索起点是2时,在[3,4,5,....,n] 中搜下一个数
.........
递归结构如下:
对于回溯法,一个重要概念就是剪枝。剪枝就是剪掉那些明显不可能出现正确结果的情况。剪枝可以避免不必要的遍历,提高运行效率。
例如下图中绿色的部分就是剪枝的部分,本题中剪枝的情况是不够k个数,也就是剩下的数就算全都选上,也不够k个数,在“树”中这种情况的“分枝”就可以剪掉。
leetcode上的一位大神,整理了回溯法和深度优先遍历的一些解析:
本题代码如下:
public class Solution {
public IList<IList<int>> Combine(int n, int k)
{
//给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
//n为宽度,k为深度
IList<IList<int>> res = new List<IList<int>>();
Backtrack77(n, k, 1, new List<int>(), res);
return res;
}
private void Backtrack77(int n, int targetDepth, int start, IList<int> path, IList<IList<int>> res)
{
if(path.Count==targetDepth)
{//递归终止条件
res.Add(path.ToList());
return;
}
for (int i = start; i <= n; i++)
{
path.Add(i);
Backtrack77(n, targetDepth, i + 1, path, res);//递归
path.RemoveAt(path.Count - 1);//回溯
}
}
}