[LeetCode][Java][回溯法]Combinations,Subsets,Permutations,Combination Sum

Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

Example:

Input: n = 4, k = 2

Output:[[2,4],[3,4], [2,3],[1,2],[1,3], [1,4]]

import java.util.*;
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new ArrayList<>();
        if(n<=0 || n<k)
            return res;
        helper(n,k,1,new ArrayList<Integer>(), res);
        return res;
    }
    private void helper(int n, int k, int start, ArrayList<Integer> item, List<List<Integer>> res)
    {
       // System.out.println(item);
        if(item.size()==k)
        {
            res.add(new ArrayList<Integer>(item));
            return;
        }
        for(int i=start;i<=n;i++)
        {
            item.add(i);
            helper(n,k,i+1,item,res);
            item.remove(item.size()-1);
        }
    }
    // public static void main(String[] args){
    //     Solution solution=new Solution();
    //     List<List<Integer>> res=solution.combine(4,2);
    //     System.out.println(res);
    // }

}

Subsets

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], []]

class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) == 0:
            return []
        if len(nums) == 1:
            return [nums]
        res = []
        for i in range(len(nums)):
            prefix = nums[i]
            rest = nums[:i] + nums[i+1:]
            for j in self.permute(rest):
                res.append([prefix]+j)
        return res

 

import java.util.*;
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res=new ArrayList<>();
        List<Integer> item=new ArrayList<>();
        helper(res,item,nums,0);//dfs
        return res;

    }
    private void helper(List<List<Integer>> res,List<Integer> item,int[] nums,int start){
        res.add(new ArrayList<Integer>(item));
        for(int i=start;i<nums.length;i++){
            item.add(nums[i]);
            helper(res,item,nums,i+1);
            item.remove(item.size()-1);
        }
    }
    // public static void main(String[] args){
    //     Solution solution=new Solution();
    //     int[] nums={1,2,3};
    //     List<List<Integer>> res=solution.subsets(nums);
    //     System.out.println(res);
    // }
}

Permutations
Input: [1,2,3]

 

Output:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

 

class Solution {
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
    ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    if(num==null || num.length==0)
        return res;
    helper(num, new boolean[num.length], new ArrayList<Integer>(), res);
    return res;
}
private void helper(int[] num, boolean[] used, ArrayList<Integer> item, ArrayList<ArrayList<Integer>> res)
{
    if(item.size() == num.length)
    {
        res.add(new ArrayList<Integer>(item));
        return;
    }
    for(int i=0;i<num.length;i++)
    {
        if(!used[i])
        {
            used[i] = true;//维护一个used数组来表示该元素是否已经在当前结果中,因为每次我们取一个元素放入结果,然后递归剩下的元素,所以不会出现重复
            item.add(num[i]);
            helper(num, used, item, res);
            item.remove(item.size()-1);
            used[i] = false;
        }
    }
}
}

Combination Sum

Input: candidates = [2,3,5], target = 8,

A solution set is:
[[2,2,2,2],[2,3,3],[3,5]]

import java.util.*;
public class Solution {
    public List<List<Integer>> combinationSum(int[] candidate,int target){
        Arrays.sort(candidate);
        List<List<Integer>> res=new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        dfs(res,temp,target,candidate,0);
        return res;
    }
    private void dfs(List<List<Integer>> res,List<Integer> temp,int target,int[] candidate,int j){
       if(target==0){
           res.add(new ArrayList<>(temp));

       }
       for(int i=j;i<candidate.length && target>=candidate[i];i++){
           temp.add(candidate[i]);
           System.out.println(temp);
           dfs(res,temp,target-candidate[i],candidate,i);
           temp.remove(temp.size()-1);
       }
    }
    // public static void main (String[] args){
    //     Solution s=new Solution();
    //     int[] temp={2,2,3,5};
    //     List<List<Integer>> res=s.combinationSum(temp,7);
    //     System.out.println(res);
    // }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值