Combination of Leetcode77.

Java stack all major league2022-08-06 08:24:20

在这里插入图片描述

题目传送地址: https://leetcode.cn/problems/combinations/

运行效率
在这里插入图片描述
解题思路
从1到n个数里面选k个数, 我打个比方吧,从1到6里面选3个数. Basically, the final result sequence is all 3或4或5或6来结尾

class Solution {

public static List<List<Integer>> combine(int n, int k) {

List<List<Integer>> res = new ArrayList<>();
//打个比方吧,从1到6里面选3个数. Basically, the final result sequence is all 3或4或5或6来结尾
for (int i = k; i <= n; i++) {

List<List<Integer>> lists = combineRecur(i, k);
res.addAll(lists);
}
return res;
}
/** * 返回所有以mending and containingk个元素的序列 * * @param m * @param k * @return */
public static List<List<Integer>> combineRecur(int m, int k) {

//处理边界情况
List<List<Integer>> result = new ArrayList<>();
if (m == k) {

List<Integer> list = new ArrayList<>();
int i = 1;
while (i <= m) {

list.add(i);
i++;
}
result.add(list);
return result;
}
if (k == 1) {

List<Integer> list = new ArrayList<>();
list.add(m);
result.add(list);
return result;
}
if (k == 2) {
 //mis already the last element in the sequence,Then there is one more element to follow1到m-1中任意选一个
int i = 1;
while (i <= m-1) {

List<Integer> list = new ArrayList<>();
list.add(i);
list.add(m);
result.add(list);
i++;
}
return result;
}
for (int i = k-1; i < m; i++) {

List<List<Integer>> combine = combineRecur(i, k - 1);
for (List<Integer> list : combine) {

List<Integer> list1 = new ArrayList<>(list);
list1.add(m);
result.add(list1);
}
}
return result;
}
}

thank
Similar articles