列出1~N中k個數其和爲給定值 Combination Sum III

問題:rem

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.io

Example 1:class

Input: k = 3, n = 7sed

Output:List

[[1,2,4]]

Example 2:co

Input: k = 3, n = 9oss

Output:new

[[1,2,6], [1,3,5], [2,3,4]]

解決:return

① 與Combination Sum, Combination Sum II相似,使用dfs解決。void

class Solution {//1ms     public List<List<Integer>> combinationSum3(int k, int n) {         List<List<Integer>> res = new ArrayList<>();         List<Integer> list = new ArrayList<Integer>();         dfs(k,n,1,list,res);         return res;     }     public void dfs(int k,int sum,int i,List<Integer> list,List<List<Integer>> res){         if (sum < 0) {             return;         }         if (sum == 0 && list.size() == k) {             res.add(new ArrayList<Integer>(list));             return;         }         for (int j = i;j <= 9 ;j ++ ) {             list.add(j);             dfs(k,sum - j,j + 1,list,res);             list.remove(list.size() - 1);         }     } }

相關文章
相關標籤/搜索