标签:combination int ArrayList List results Combinations new
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);
}
}
}
标签:combination,int,ArrayList,List,results,Combinations,new 来源: https://www.cnblogs.com/blackraven25/p/15110040.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。