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-11-27Rocket消息队列资料:新手入门指南
- 2024-11-27rocket消息队资料详解与入门指南
- 2024-11-27RocketMQ底层原理资料详解入门教程
- 2024-11-27RocketMQ项目开发资料:新手入门教程
- 2024-11-27RocketMQ项目开发资料详解
- 2024-11-27RocketMQ消息中间件资料入门教程
- 2024-11-27初学者指南:深入了解RocketMQ源码资料
- 2024-11-27Rocket消息队列学习入门指南
- 2024-11-26Rocket消息中间件教程:新手入门详解
- 2024-11-26RocketMQ项目开发教程:新手入门指南