Advertisement
Guest User

Untitled

a guest
Sep 19th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. // Runtime: 10 ms, faster than 75.67% of Java online submissions for Combinations.
  2. // Memory Usage: 39.3 MB, less than 82.61% of Java online submissions for Combinations.
  3. class Solution {
  4.     public List<List<Integer>> combine(int n, int k) {
  5.         List<List<Integer>> results = new ArrayList<List<Integer>>();
  6.         int[] current = new int[k];
  7.         combine(n, k, 0, current, results);
  8.         return results;
  9.     }
  10.    
  11.     private void combine(int n, int k, int pos, int[] current, List<List<Integer>> results) {
  12.         if (pos >= k) {
  13.             List<Integer> result = new ArrayList<Integer>();
  14.             for (int x: current) {
  15.                 result.add(x);
  16.             }
  17.             results.add(result);
  18.             return;
  19.         }
  20.        
  21.         int from = (pos == 0) ? 1: current[pos-1] + 1;
  22.         for (int i = from; i <= n; i++) {
  23.             current[pos] = i;
  24.             combine(n, k, pos + 1, current, results);
  25.         }
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement