用回溯算法解决集合问题(Java实现)

1.1题目:组合

给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。

示例:

输入: n = 4, k = 2
输出:
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

解决代码:

class Solution {
    int n;
    int k;
    List<List<Integer>> res = new LinkedList<>(); 
    
    public List<List<Integer>> combine(int n, int k) {
        this.n = n;
        this.k = k;
        
        middleMeth(1,new LinkedList<Integer>());
        return res;
    }
    
    public void middleMeth(int temp,LinkedList<Integer> list){
        if(list.size() == k){
            res.add(new LinkedList(list));
        }
        
        for(int i = temp; i < n + 1 ;++i){
            list.add(i);
            middleMeth(i + 1,list);
            list.removeLast();
        }
    }
}

 1.2题目:子集

给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: nums = [1,2,3]
输出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

解决代码:

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        MethodMiddle(0,nums,res,new ArrayList<>());
        
        return res;
    }
    
    public void MethodMiddle(int i,int[] nums,List<List<Integer>> res,List<Integer> list){
        res.add(new ArrayList<Integer>(list));
        
        for(int j = i;j < nums.length;j++){
            list.add(nums[j]);
            MethodMiddle(j + 1,nums,res,list);
            list.remove(list.size() - 1);
        }
    }
}

  1.3题目:子集II

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: [1,2,2]
输出:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

解决代码:

 

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        
        List<List<Integer>> res = new ArrayList<>();
        
        Arrays.sort(nums);
        MethodMidd(0,nums,res,new ArrayList<>());
        
        return res;
        
    }
    
    public void MethodMidd(int index,int[] nums,List<List<Integer>> res,List<Integer> list){
        res.add(new ArrayList<>(list));
        
        for(int i = index;i < nums.length;i++){
            if(i > index && nums[i - 1] == nums[i]){
                continue;
            }
            list.add(nums[i]);
            MethodMidd(i + 1,nums,res,list);
            list.remove(list.size() - 1);
        }
    } 
}

 

posted @ 2019-07-18 14:47  离愁i  阅读(744)  评论(0编辑  收藏  举报