Fast java solution with math


  • 2
    G
    public static List<List<Integer>> combine(int n, int k) {
      List<List<Integer>> retVal = new ArrayList<>();
      List<Integer> last = new ArrayList<>();
      for (int j = 1; j <= k; j++) {
        last.add(j);
      }
      retVal.add(last);
      while (last.get(0) != n-k+1 || last.get(k-1) != n) {
        List<Integer> val = new ArrayList<>();
        for (int i = k; i >= 0; i--) {
          if (last.get(i-1) < n-(k-i)) {
            int q = last.get(i-1);
            for (int j = 0; j < i-1; j++) {
              val.add(last.get(j));
            }
            for (int l = i-1, s = 1; l < k; l++, s++) {
                val.add(q+s);
            }
            break;
          } 
        }
        retVal.add(val);
        last = val;
      }
      return retVal;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.