Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Backtracking can be solved always as follows:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> list = new ArrayList();
List<Integer> tmp = new ArrayList<Integer>();
helper(list,tmp,nums,0);
return list;
}
void helper(List<List<Integer>> list,List<Integer> tmp,int[] nums,int start){
list.add(new ArrayList<>(tmp));
for(int i=start;i<nums.length;i++){
tmp.add(nums[i]);
helper(list,tmp,nums,i+1);
tmp.remove(tmp.size()-1);
}
}
}
Pick a starting point.
while(Problem is not solved)
For each path from the starting point.
check if selected path is safe, if yes select it
and make recursive call to rest of the problem
before which undo the current move.
End For
If none of the move works out, return false, NO SOLUTON.