Seeking power set
Using backtracking, the main view is that each element in the collection is in and out of the list, and a new solution is created in and out;
Import Java.util.arraylist;import Java.util.list;public class P78 {public list<list<integer>> Subsets (int[] nums) { list<list<integer>> result=new arraylist<list<integer>> (); Backtrack (nums,0,new arraylist<integer> (), result); return result; } Backtracking private void backtrack (int []nums,int start,list<integer> list,list<list<integer>> Result { //each time the element list is added to result Result.add (new arraylist<> (list)); for (int i=start;i<nums.length;i++) { //unordered, each element traverses backwards List.add (nums[i]); Joins the current element to the linked list backtrack (nums,i+1,list,result); List.remove (List.size ()-1); Delete the last Element}}}
shallow copy deep copy problem of list
The List.add (e) method passes in an object that actually holds a reference to the object, so even if the value of E is changed after the Add method executes, the E object that you want to store the different values is going to pass in a deep copy of E at each add (usually using the new E (E)) to achieve
public class Testlistadd {public static void main (String argv[]) {testlistadd temp=new testlistadd (); Temp.test (); The public void Test () {/** * Tests string because the string is immutable and therefore teststring= "456"; when it is actually a new object, the "123" that the list first stores is not changed */String list<string> stringlist=new arraylist<> (); String teststring= "123"; Stringlist.add (teststring); Teststring= "456"; System.out.println (stringlist.get (0)); /** * Test object because List holds a object, so after using Add, a will also change the value of a (*/list<student> studentlist=new Arraylis T<> (); Student A=new Student (18); Studentlist.add (a); A.setage (20); System.out.println (Studentlist.get (0). Getage ()); /** * Similar to object, to add an immutable List, add only one of its deep copies new ArrayList (a) */list<list<integer>> Lis Tlist=new arraylist<> (); List<integer> list1=new arraylist<> (); List1.add (1); Listlist.add (List1); Listlist.add (New arraylist<> (List1)); List1.add (2); for (List l:listlist) {for (Object integer:l) {System.out.print (integer+ "--"); } System.out.println (); }} class student{private int age; Student () {} student (int age) {this.age=age;} public void Setage (int.) {this.age=age; } public int Getage () {return age; } }}
A shallow copy deep copy problem of Java power set and list