Combined algorithm-deep Priority Search

Source: Internet
Author: User

Preface LeetCode has many string combination questions. I have previously written a binary method to solve this type of problem. Original article: string combination algorithm
Here, we will introduce a method to solve the problem of string combination using dfs.

A typical concept is dfs. Where is the starting point for adding an int pos record subset? When the loop ends, the previous layer needs to delete the newly added element.
Take the set [1, 2, 3] as an example:
Pos =-1, []
Pos = 0, [1]
Pos = 1, [1, 2]
Pos = 2, [1, 2, 3]
Pos = 2, delete 3
Pos = 1, delete 2
Pos = 2, [1, 3]
Pos = 1, delete 3
Pos = 0, delete 1
Pos = 1, [2]
Pos = 2, [2, 3]
Pos = 1, delete 3
Pos = 0, delete 2
Pos = 3, [3]

Question Given a set of distinct integers, S, return all possible subsets.

Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1, 2, 3], a solution is:

[
[3],
[1],
[2],
[1, 2, 3],
[1, 3],
[2, 3],
[1, 2],
[]
]

AC code

import java.util.ArrayList;import java.util.Arrays;public class SubSets {    public static ArrayList> subsetsWithDup(int[] num) {        ArrayList> res = new ArrayList>();        ArrayList
 
   tmp = new ArrayList
  
   ();        Arrays.sort(num);        res.add(tmp);        dfs(0, num, tmp, res);        return res;    }    public static void dfs(int pos, int[] num, ArrayList
   
     tmp,            ArrayList> res) {        if (pos >= num.length) {            return;        } else {            for (int i = pos; i < num.length; i++) {                tmp.add(num[i]);                res.add(new ArrayList
    
     (tmp));                dfs(i + 1, num, tmp, res);                tmp.remove(tmp.size() - 1);            }        }    }}
    
   
  
 



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.