本文共 951 字,大约阅读时间需要 3 分钟。
组合问题,即给定两个整数n和k,返回1到n中所有可能的k个数的组合。以下是解决方案:
import java.util.ArrayList;import java.util.List;public class Solution { public List > combine(int n, int k) { List > son = new ArrayList<>(); List parent = new ArrayList<>(); dfs(1, n, k); return parent; } public void dfs(int cur, int n, int k) { if (cur == n + 1) { if (son.size() == k) { parent.add(new ArrayList(son)); } return; } son.add(cur); dfs(cur + 1, n, k); son.remove(son.size() - 1); dfs(cur + 1, n, k); }}
cur超过n时,检查当前组合是否满足k的条件。以下是代码运行示例:
combine(4, 2)返回:[ [2, 4], [3, 4], [2, 3], [1, 2], [1, 3], [1, 4]]
这个解决方案高效且简洁,能够处理最大的n值和组合数。
转载地址:http://uzzcz.baihongyu.com/