216. Combination Sum III

class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
      List<List<Integer>> result = new ArrayList<>();
      List<Integer> current = new ArrayList<>();
      dfs(k, n, result, current, 1);
      return result; 
    }
    private void dfs(int k, int n, List<List<Integer>> result, List<Integer> current, int start){
      if(current.size() > k){
        return;
      }else if (current.size() == k && n == 0){
        result.add(new ArrayList<>(current));
      }else{
        for(int i = start; i <= 9; i++){
          current.add(i);
          dfs(k, n - i, result, current, i+1);
          current.remove(current.size() - 1);
        }
      }
    }
}

猜你喜欢

转载自www.cnblogs.com/tobeabetterpig/p/9327114.html