Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Runtime: 10 ms, faster than 75.67% of Java online submissions for Combinations.
- // Memory Usage: 39.3 MB, less than 82.61% of Java online submissions for Combinations.
- class Solution {
- public List<List<Integer>> combine(int n, int k) {
- List<List<Integer>> results = new ArrayList<List<Integer>>();
- int[] current = new int[k];
- combine(n, k, 0, current, results);
- return results;
- }
- private void combine(int n, int k, int pos, int[] current, List<List<Integer>> results) {
- if (pos >= k) {
- List<Integer> result = new ArrayList<Integer>();
- for (int x: current) {
- result.add(x);
- }
- results.add(result);
- return;
- }
- int from = (pos == 0) ? 1: current[pos-1] + 1;
- for (int i = from; i <= n; i++) {
- current[pos] = i;
- combine(n, k, pos + 1, current, results);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement