publicList<List<Integer>>subsets(int[] nums) {List<List<Integer>> list =newArrayList<>();Arrays.sort(nums);backtrack(list,newArrayList<>(), nums,0);return list;}privatevoidbacktrack(List<List<Integer>> list ,List<Integer> tempList,int [] nums,int start){list.add(newArrayList<>(tempList));for(int i = start; i <nums.length; i++){tempList.add(nums[i]);backtrack(list, tempList, nums, i +1);tempList.remove(tempList.size() -1); }}
publicList<List<Integer>>subsetsWithDup(int[] nums) {List<List<Integer>> list =newArrayList<>();Arrays.sort(nums);backtrack(list,newArrayList<>(), nums,0);return list;}privatevoidbacktrack(List<List<Integer>> list,List<Integer> tempList,int [] nums,int start){list.add(newArrayList<>(tempList));for(int i = start; i <nums.length; i++){if(i > start && nums[i] == nums[i-1]) continue; // skip duplicatestempList.add(nums[i]);backtrack(list, tempList, nums, i +1);tempList.remove(tempList.size() -1); }}
publicList<List<Integer>>permute(int[] nums) {List<List<Integer>> list =newArrayList<>();// Arrays.sort(nums); // not necessarybacktrack(list,newArrayList<>(), nums);return list;}privatevoidbacktrack(List<List<Integer>> list,List<Integer> tempList,int [] nums){if(tempList.size() ==nums.length){list.add(newArrayList<>(tempList)); } else{for(int i =0; i <nums.length; i++){ if(tempList.contains(nums[i])) continue; // element already exists, skiptempList.add(nums[i]);backtrack(list, tempList, nums);tempList.remove(tempList.size() -1); } }}