@@ -0,0 +1,1786 @@
+/*%0AFind 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.%0A%0AEnsure that numbers within the set are sorted in ascending order.%0A%0AExample 1:%0A%0AInput: k = 3, n = 7%0A%0AOutput:%0A%0A%5B%5B1,2,4%5D%5D%0A%0A%0AExample 2:%0A%0AInput: k = 3, n = 9%0A%0AOutput:%0A%0A%5B%5B1,2,6%5D, %5B1,3,5%5D, %5B2,3,4%5D%5D%0A%0A*/%0A%0Aimport java.io.*;%0Aimport java.util.*;%0A%0Apublic class CombinationSumIII %7B%0A    private static List%3CList%3CInteger%3E%3E res = new ArrayList%3CList%3CInteger%3E%3E();%0A%09public static List%3CList%3CInteger%3E%3E combinationSum3(int k, int n) %7B%0A        if( k %3C= 0 %7C%7C n %3C= 0) return res;%0A        comRe(k, n, 1, 0, new ArrayList%3CInteger%3E());%0A        return res;%0A    %7D%0A    %0A    public static void comRe(int k, int n, int startn, int sum, List%3CInteger%3E a)%7B%0A        if(a.size() %3E k) return;%0A        if(sum %3E n) return;%0A        if(a.size() == k && sum == n)%7B%0A            res.add(new ArrayList%3CInteger%3E(a));%0A        %7D%0A        for(int i = startn; i %3C 10; i++)%7B%0A            a.add(i);%0A            comRe(k, n, i+1, sum + i, a);%0A            a.remove(a.size()-1);%0A        %7D%0A        return;%0A    %7D%09%0A%09%0A%09public static void dispArray2D(List%3CList%3CInteger%3E%3E res)%7B%0A%09%09for(int i = 0; i %3C res.size(); i++)%7B    %0A%09%09%09for(int j = 0; j %3C res.get(i).size(); j++)%7B%0A%09%09%09%09System.out.print(res.get(i).get(j) + %22 %22);   // note: res%5Bi%5D%5Bj%5D%0A%09%09%09%7D%0A%09%09%09System.out.println();%0A%09%09%7D%0A%09%7D%0A%09public static void main(String%5B%5D args) %7B%0A%09%09Scanner reader = new Scanner(System.in); %0A%09%09System.out.println(%22combination sum with given length k and sum n%22);%0A%09%09System.out.println(%22Enter k: %22);%0A%09%09int k = reader.nextInt();%0A%09%09System.out.println(%22Enter n: %22);%0A%09%09int n = reader.nextInt();%0A%09%09List%3CList%3CInteger%3E%3E r = combinationSum3(k, n);%0A%09%09System.out.println(%22results: %22);%0A%09%09dispArray2D(r);%0A%09%09return;%0A%09%7D%09%0A%7D%0A

combination sum given length