Iterative method using java, medium-understand


  • 0
    P
            List<List<Integer>> result = new ArrayList<>();
            List<List<Integer>> tmpResult;
            if (k == 0) return result;
            int count = 1;
            for (int i = 1; i <= n; i++) {
                List<Integer> tmp = new ArrayList<>();
                tmp.add(i);
                result.add(tmp);
            }
            while (count < k) {
                tmpResult = new ArrayList<>(result);
                result = new ArrayList<>();
                count++;
                for (List<Integer> sorted : tmpResult) {
                    if (sorted.get(sorted.size() - 1) + 1 > n) continue;
                    List<List<Integer>> newResult = new ArrayList<>();
                    for (int i = sorted.get(sorted.size() - 1) + 1; i <= n; i++) {
                        List<Integer> tmp = new ArrayList<>(sorted);
                        tmp.add(i);
                        newResult.add(tmp);
                    }
                    result.addAll(newResult);
                }
            }
            return result;

Log in to reply
 

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