Uncategorized

Combinations [LC # 77]





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

Input: n = 4, k = 2
Output:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> current = new ArrayList<>();
        
        dfs(result, current, n, k, 1);
        
        return result;
        
    }
    
    private void dfs(List<List<Integer>> result, 
                     List<Integer> current, 
                     int n, int k, int pos){
        
        if(current.size() == k){
            result.add(new ArrayList<>(current));
            return;
        }
        
        if(pos > n) return;
        
        for(int i = pos; i <= n; i++){
            current.add(i);
            dfs(result, current, n, k, i + 1);
            current.remove(current.size() - 1);
        }
    }
        
}

You never change your life until you step out of your comfort zone; change begins at the end of your comfort zone