Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Your runtime beats 87.12 % of java
- class Solution {
- public List<List<Integer>> combine(int n, int k) {
- List<List<Integer>> results = new ArrayList<List<Integer>>();
- if (k > n) return results;
- int[] current = new int[k];
- for (int i=0; i < k; i++) current[i] = i + 1;
- for(;;) {
- List<Integer> result = new ArrayList<>();
- for (int x: current) {
- result.add(x);
- }
- results.add(result);
- int p = k - 1;
- while (p >= 0 && current[p] + k - p > n) {
- p--;
- }
- if (p < 0) break;
- current[p] += 1;
- for (int i = p + 1; i < k; i++) current[i] = current[i - 1] + 1;
- }
- return results;
- }
- }
- // 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