![在这里插入图片描述](https://img-blog.csdnimg.cn/20200908084941317.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L01hc29uOTc=,size_16,color_FFFFFF,t_70#pic_center)
我用的方法是 搜索回溯的方法。
class Solution {
public static void main(String[] args) {
Solution s = new Solution();
List<List<Integer>> list = s.combine(4, 2);
System.out.println(list.toString());
}
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new LinkedList<>();
boolean[] candidate = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
LinkedList<Integer> tmp = new LinkedList<>();
tmp.add(i);
candidate[i] = true;
dfs(candidate, res, 1, k, tmp, n, i);
candidate[i] = false;
}
return res;
}
private void dfs(boolean[] candidate, List<List<Integer>> res, int count, int k, LinkedList<Integer> tmp, int n,int ii) {
if (count == k) {
LinkedList<Integer> clone = new LinkedList<>(tmp);
res.add(clone);
return;
}
if(ii == n) return;
for (int i = ii; i <= n; i++) {
if (!candidate[i]) {
tmp.add(i);
candidate[i] = true;
dfs(candidate, res, count + 1, k, tmp, n, i);
candidate[i] = false;
tmp.remove(tmp.size() - 1);
}
}
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200908085218522.png#pic_center)
速度有点慢,考虑剪枝来提速一下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/2020090808562239.png#pic_center)
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200908085557678.png#pic_center)
class Solution {
public static void main(String[] args) {
Solution s = new Solution();
List<List<Integer>> list = s.combine(4, 2);
System.out.println(list.toString());
}
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new LinkedList<>();
boolean[] candidate = new boolean[n + 1];
for (int i = 1; i <= n; i++) {
LinkedList<Integer> tmp = new LinkedList<>();
tmp.add(i);
candidate[i] = true;
dfs(candidate, res, 1, k, tmp, n, i);
candidate[i] = false;
}
return res;
}
private void dfs(boolean[] candidate, List<List<Integer>> res, int count, int k, LinkedList<Integer> tmp, int n,
int ii) {
if (count == k) {
LinkedList<Integer> clone = new LinkedList<>(tmp);
res.add(clone);
return;
}
if ((n - ii) < (k - count)) return;
for (int i = ii; i <= n; i++) {
if (!candidate[i]) {
tmp.add(i);
candidate[i] = true;
dfs(candidate, res, count + 1, k, tmp, n, i);
candidate[i] = false;
tmp.remove(tmp.size() - 1);
}
}
}
}