Java Solution beats ~90%


  • 0
    G
    public List<List<Integer>> combine(int n, int k) {
            List<List<Integer>> result = new ArrayList<>();
            if (n <=0 || k <=0 || k > n) {
                return result;
            }
            int[] nums = new int[k];
            helper(nums, 1, 0, result, n);
            return result;
        }
        
        // start denotes that you add numbers from [start, n]
        // index denotes the index at which you add numbers from [start, n]
        public void helper(int[] nums, int start, int index, List<List<Integer>> result, int n) {
            if (index == nums.length) {
                List<Integer> temp = new ArrayList<>();
                for (int i=0;i<nums.length;i++) {
                    temp.add(nums[i]);
                }
                result.add(temp);
                return;
            }
            for (int i=start;i<=n;i++) {
                nums[index] = i;
                helper(nums, i+1, index+1, result, n);
            }
        }

  • 0
    J

    No, this is still DFS. You didn't record previous status.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.