Java solution within 4ms


  • 0
    D

    public class Solution {
    public List<List<Integer>> combine(int n, int k) {
    List<List<Integer>> result = new ArrayList<>();
    if (k == 0 || k > n) {
    return result;
    }

        boolean[] used = new boolean[n];
        getResult(result, new ArrayList<Integer>(), used, 0, n, k, 0);
        return result;
    }
    
    public void getResult(List<List<Integer>> result, List<Integer> row, boolean[] used, int Nused, int n, int k, int start) {
        if (Nused >= k) {
            result.add(new ArrayList<Integer>(row));
            return;
        }
        for (int i = start; i < n-k+Nused+1; i++) {
            if (!used[i]) {
                row.add(i+1);
                Nused++;
                used[i] = true;
                getResult(result, row, used, Nused, n, k, i+1);
                row.remove(row.size()-1);
                Nused--;
                used[i] = false;
            }
        }
    }
    

    }


Log in to reply
 

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