Share my Java easy understanding iterative solution


  • 0
    A
    public class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            Arrays.sort(nums);
            List<List<Integer>> output=new LinkedList<List<Integer>> ();
            List<Integer> result=new LinkedList<Integer> ();
            int size=nums.length;
            if(size<=0)   return output;
            output.add(result);
            List<List<Integer>> backup;
            for(int i=0;i<size;i++)
            {
                backup=new LinkedList<List<Integer>> (output);
                for(List<Integer> temp:backup)
                {
                    result=new LinkedList<Integer> (temp);
                    result.add(nums[i]);
                    output.add(result);
                }
            }
            return output;
        }
    }

  • 0
    W

    my easy solution using java with recursion and backtracking

     public class Solution {
    
    public List<List<Integer>> subsets(int[] nums) {
       
       List<Integer> sub = new ArrayList<Integer>();
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        Arrays.sort(nums);
        combination(nums, result, sub, 0);
        return result;
    }
    public void combination(int[] nums, List<List<Integer>> result, List<Integer> sub, int start){
        result.add(new ArrayList(sub));
        for(int i = start; i < nums.length; i++){
            if(i > start && nums[i] == nums[i-1]){
                continue;
            }
            sub.add(nums[i]);
            combination(nums, result, sub, i+1);
            sub.remove(sub.size() - 1);
        }
       
      return;
    }
    

    }


Log in to reply
 

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