​原题链接​

不要自卑,去提升实力
互联网行业谁技术牛谁是爹
如果文章可以带给你能量,那是最好的事!请相信自己,加油o~

77.组合

给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

解题思路:

  • 和全排列算法差不多
  • 当临时遍历达到k值,将它计入
  • startIndex为开始的下标
  • 每当遍历一次,下标+1,添加下一个元素
  • 当本次元素添加完后,清除本个元素,继续下次搜索

代码:

/**
*作者:魏宝航
*2020年11月29日,上午9:54
*/
class Solution {
List<List<Integer>> list = new LinkedList<>();
List<Integer> temp = new LinkedList<>();
public void fn(int n,int k,int startIndex){
if(temp.size()==k){
list.add(new LinkedList(temp));
return;
}
for(int i=startIndex;i<=n-(k-temp.size())+1;i++){
temp.add(i);
fn(n,k,i+1);
temp.remove(temp.size()-1);
}
}
public List<List<Integer>> combine(int n, int k) {
fn(n,k,1);
return list;
}
}