77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example, If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

backtracking

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

        bt(1, n, k, new ArrayList<Integer>());
        return res;

    }

    private void bt(int start, int n, int k, List<Integer> list){
        if(k == 0){
            List<Integer> t = new ArrayList<>(list);
            res.add(t);
            return;
        }

        for(int i= start; i<=n; i++){
            list.add(i);
            bt(i+1, n, k-1, list);
            list.remove(list.size()-1);
        }    
    }


}

results matching ""

    No results matching ""