1. 程式人生 > >78/90 Subsets --back tracking

78/90 Subsets --back tracking

78  nums 元素沒有重複, 求subsets, 共有 2^n

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

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

90. 有重複元素情況下求組合數, 唯一需要注意的是如何去重: 

 if(i==start || i>start && nums[i]!= nums[i-1])
Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        Arrays.sort(nums);
        dfs(0, new ArrayList<>(),  result, nums);
        return result;
    }
    
    private void dfs(int start, List<Integer> curResult, List<List<Integer>> result, int[] nums){
        
        result.add(new ArrayList<>(curResult));
        
        if(curResult.size() == nums.length){
            return;
        }
        
        for(int i=start; i<nums.length; i++){
            if(i==start || i>start && nums[i]!= nums[i-1]){
            curResult.add(nums[i]);
            dfs(i+1, curResult, result,nums);
            curResult.remove(curResult.size()-1);
          }
        }  
    }
}