Combinations
2021/8/6 23:35:54
本文主要是介绍Combinations,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Link: https://leetcode.com/problems/combinations/
Constraint:
1 <= n <= 20 1 <= k <= n ==> k is always valid
Idea
Initialize an structure to keep track of whether a number has been visited or not
Initialize a list to keep track of the combination visited so far
Search:
If the size of combinatin list is equal to k, add it to final result list
For each number i in range [1, N]:
if i is not visited:
add the number to the combination list, mark this number as visited
repeat this earch on other numbers recursively, with the starting index from (i + 1)
remove the number i from the combination, mark it in the as unvisited
Code
class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> results = new ArrayList<>(); search(n, k, 1, new boolean[n + 1], new ArrayList<Integer>(), results); return results; } private void search(int n, int k, int start, boolean[] visited, List<Integer> combination, List<List<Integer>> results) { if (combination.size() == k) { results.add(new ArrayList<>(combination)); return; } for (int i = start; i <= n; i++) { if (!visited[i]) { visited[i] = true; combination.add(i); search(n, k, i + 1, visited, combination, results); combination.remove(combination.size() - 1); visited[i] = false; } } } }
- Time: It would be equal to C(n, k), n choose k.
- Space:
Slightly better version without the need to use boolean array:
class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> results = new ArrayList<>(); search(n, k, 1, new ArrayList<Integer>(), results); return results; } private void search(int n, int k, int index, List<Integer> comb, List<List<Integer>> results) { if (comb.size() == k) { results.add(new ArrayList<Integer>(comb)); return; } for (int i = index; i <= n; i++) { comb.add(i); search(n, k, i + 1, comb, results); comb.remove(comb.size() - 1); } } }
这篇关于Combinations的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-30uniAPP 实现全屏左右滚动滚动的效果-icode9专业技术文章分享
- 2024-06-30如何在本地使用授权或插件-icode9专业技术文章分享
- 2024-06-30伪静态规则配置方法汇总-icode9专业技术文章分享
- 2024-06-29易优CMS安装常见问题汇总-icode9专业技术文章分享
- 2024-06-28易优新手必读安装教程-icode9专业技术文章分享
- 2024-06-28忘记eyoucms后台密码怎么办?-icode9专业技术文章分享
- 2024-06-26终极指南:Scrum中如何设置需求优先级
- 2024-06-26AI大模型企业应用实战(25)-为Langchain Agent添加记忆功能
- 2024-06-26小白家庭 nas 搭建方案-icode9专业技术文章分享
- 2024-06-23AI大模型企业应用实战(14)-langchain的Embedding