|
| 1 | +# Intuition |
| 2 | +<!-- Describe your first thoughts on how to solve this problem. --> |
| 3 | +Little change the Subset problem ( 78 ) |
| 4 | + |
| 5 | +# Approach |
| 6 | +<!-- Describe your approach to solving the problem. --> |
| 7 | +Simply extract subsets of length 'k' after finding all subsets of[ 1, 2, ... , n] |
| 8 | + |
| 9 | +To find all subsets : |
| 10 | +( 78. Subsets : https://leetcode.com/problems/subsets/solutions/3740278/78-subsets-simple-intuition/ ) |
| 11 | + |
| 12 | +Just attach the current number to every single subsets created before. |
| 13 | + |
| 14 | +nums = [1, 2, 3, 4] |
| 15 | +subsets |
| 16 | +[ |
| 17 | +[ ] , |
| 18 | +[ 1 ] , |
| 19 | +[ 2 ] , [ 1, 2 ] , |
| 20 | +[ 3 ] , [ 1, 3 ] , [ 2, 3 ], [ 1, 2, 3 ] , |
| 21 | +[ 4 ] , [ 1, 4 ] , [ 2, 4 ] , [ 1, 2, 4 ] , [ 3, 4 ] , [ 1, 3, 4 ] , [ 2, 3, 4 ] , [ 1, 2, 3, 4 ] |
| 22 | +] |
| 23 | + |
| 24 | +After extracting of '2' length : |
| 25 | + |
| 26 | +[ 1, 2 ] , [ 1, 3 ] , [ 2, 3 ] , [ 1, 4 ] , [ 2, 4 ] , [ 3, 4 ] |
| 27 | + |
| 28 | + |
| 29 | +Have a look at the code , still have any confusion then please let me know in the comments |
| 30 | +Keep Solving.:) |
| 31 | + |
| 32 | + |
| 33 | +# Complexity |
| 34 | +- Time complexity : $$O(n^2)$$ |
| 35 | +<!-- Add your time complexity here, e.g. $$O(n)$$ --> |
| 36 | + |
| 37 | +- Space complexity: |
| 38 | +<!-- Add your space complexity here, e.g. $$O(n)$$ --> |
| 39 | + |
| 40 | +# Code |
| 41 | +``` |
| 42 | +class Solution { |
| 43 | + public List<List<Integer>> combine(int n, int k) { |
| 44 | + List<List<Integer>> ans = new ArrayList<>(); // to store answer of list of length 'k' |
| 45 | + List<List<Integer>> li = new ArrayList<>(); // to store all subsets |
| 46 | + List<Integer> t = new ArrayList<>(); |
| 47 | + li.add( t); |
| 48 | +
|
| 49 | + int s = li.size(); |
| 50 | + for( int i = 1; i <= n; i++){ |
| 51 | + for( int j = 0; j < s; j++){ |
| 52 | + List<Integer> tl = new ArrayList<>(li.get(j)); |
| 53 | + tl.add( i); |
| 54 | + //System.out.println( tl.toString()); |
| 55 | + if( tl.size() == k){ // if current formed subset is of length 'k' then add to answer list |
| 56 | + ans.add( tl); |
| 57 | + } |
| 58 | +
|
| 59 | + li.add( tl); |
| 60 | + } |
| 61 | + s = li.size(); |
| 62 | + } |
| 63 | + //System.out.println( li.toString()); // to print all subsets |
| 64 | + return ans; |
| 65 | + } |
| 66 | +} |
| 67 | +``` |
0 commit comments