Add to List 77. Combinations
2017-06-29 11:36
363 查看
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> data = new ArrayList<>();
if (n == 0 || n < k)
return data;
helper(data, new LinkedList<Integer>(), n, k);
return data;
}
public void helper(List<List<Integer>> data, List<Integer> temp, int n, int k) {
for (int i = n; i >= k; --i) {
if (k == 0) {
data.add(temp);
break;
} else {
LinkedList<Integer> next = new LinkedList<>(temp);
next.addFirst(i);
helper(data, next, i - 1, k - 1);
}
}
}
}
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> data = new ArrayList<>();
if (n == 0 || n < k)
return data;
helper(data, new LinkedList<Integer>(), n, k);
return data;
}
public void helper(List<List<Integer>> data, List<Integer> temp, int n, int k) {
for (int i = n; i >= k; --i) {
if (k == 0) {
data.add(temp);
break;
} else {
LinkedList<Integer> next = new LinkedList<>(temp);
next.addFirst(i);
helper(data, next, i - 1, k - 1);
}
}
}
}
相关文章推荐
- 104. Maximum Depth of Binary Tree Add to List DescriptionHintsSubmissions
- java.lang.IllegalStateException:Cannot add header view to list==setAdapter has already been called.
- SharePoint自动化系列——Add content type to list.
- Android Studio First Run unable to access Android SDK add-on-list
- 第一次安装android studio时候弹出unable to access android sdk add-on list解决方法
- ParseResult Exception:java.lang.IllegalStateException: Cannot add header view to list -- setAdapter
- Add to List 542. 01 Matrix
- 【LeetCode】Add to List 606. Construct String from Binary Tree
- 492. Construct the Rectangle Add to List
- leetcode- Add to List 669. Trim a Binary Search Tree
- Add to List 657. Judge Route Circle
- Add to List 658. Find K Closest Elements
- java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been calle
- Add to List 447. Number of Boomerangs
- Problem Code: PSHTTR Add problem to Todo list Submit Tweet
- 【LeetCode】417. Pacific Atlantic Water Flow Add to List
- Add to List 611. Valid Triangle Number
- Add to List 617. Merge Two Binary Trees
- LeetCode406. Queue Reconstruction by Height Add to List