diff --git a/leetcode/077-Combination.java b/leetcode/077-Combination.java new file mode 100644 index 0000000..8330036 --- /dev/null +++ b/leetcode/077-Combination.java @@ -0,0 +1,31 @@ +import java.util.*; +class Solution { + + public static List> combine(int n, int k) { + List> result = new ArrayList<>(); + exploreCombinations(n, k, 1, new ArrayList(), result); + return result; + } + + private static void exploreCombinations(int n, int k, int offset, + List snippet, + List> result) { + if (snippet.size() == k) { + result.add(new ArrayList<>(snippet)); + return; + } + final int spaceLeftInSnippet = k - snippet.size(); + for (int i = offset; i <= n && spaceLeftInSnippet <= n - i + 1 ; ++i) { + snippet.add(i); + exploreCombinations(n, k, i + 1, snippet , result); + snippet.remove(snippet.size() - 1); + } + } + + public static void main(String[] args){ + Scanner sc=new Scanner(System.in); + int n=sc.nextInt(); + int k=sc.nextInt(); + combine(n,k); + } +}