Leetcode--78. 子集
給定一組不含重復元素的整數數組?nums,返回該數組所有可能的子集(冪集)。
說明:解集不能包含重復的子集。
示例:
輸入: nums = [1,2,3]
輸出:
[
? [3],
??[1],
??[2],
??[1,2,3],
??[1,3],
??[2,3],
??[1,2],
??[]
]
思路:回溯法
提交的代碼:
給定一組不含重復元素的整數數組?nums,返回該數組所有可能的子集(冪集)。
說明:解集不能包含重復的子集。
示例:
輸入: nums = [1,2,3]
輸出:
[
? [3],
??[1],
??[2],
??[1,2,3],
??[1,3],
??[2,3],
??[1,2],
??[]
]
提交的代碼:
class Solution {
? ? public static List<List<Integer>> subsets(int[] nums) {
? ? ? ?// Arrays.sort(nums);
? ? ? ? List<List<Integer>> result = new ArrayList();
? ? ? ? List<Integer> list = new ArrayList();
? ? ? ? result = find(0,nums,list,result);
? ? ? ? return result;
? ? }
? ? public static List<List<Integer>> find(int begin,int[] nums,List<Integer> list,List<List<Integer>> result)
? ? {
? ? ?? ?int i;
? ? ?? ?result.add(new ArrayList(list));
? ? ?? ?for(i=begin;i<nums.length;i++)
? ? ?? ?{
? ? ?? ??? ?list.add(nums[i]);
? ? ?? ??? ?find(i+1,nums,list,result);
? ? ?? ??? ?list.remove(list.size()-1);
? ? ?? ?}
? ? ?? ?return result;
? ? }
}
完整的代碼:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Solution78 {
? ? public static List<List<Integer>> subsets(int[] nums) {
? ? ? ?// Arrays.sort(nums);
? ? ? ? List<List<Integer>> result = new ArrayList();
? ? ? ? List<Integer> list = new ArrayList();
? ? ? ? result = find(0,nums,list,result);
? ? ? ? return result;
? ? }
? ? public static List<List<Integer>> find(int begin,int[] nums,List<Integer> list,List<List<Integer>> result)
? ? {
? ? ?? ?int i;
? ? ?? ?result.add(new ArrayList(list));
? ? ?? ?for(i=begin;i<nums.length;i++)
? ? ?? ?{
? ? ?? ??? ?list.add(nums[i]);
? ? ?? ??? ?find(i+1,nums,list,result);
? ? ?? ??? ?list.remove(list.size()-1);
? ? ?? ?}
? ? ?? ?return result;
? ? }
?? ?public static void main(String[] args)
?? ?{
?? ??? ?int[] nums = {1,2,3};
?? ??? ?List<List<Integer>> list = new ArrayList();
?? ??? ?list = subsets(nums);
?? ??? ?Iterator<List<Integer>> it = list.iterator();
?? ??? ?int count = 1;
?? ??? ?while(it.hasNext()) {
?? ??? ??? ?Iterator<Integer> itt = it.next().iterator();
?? ??? ??? ?//System.out.println(" "+count+" ");
?? ??? ??? ?while(itt.hasNext()) {
?? ??? ??? ??? ?System.out.print(itt.next()+" ");
?? ??? ??? ?}
?? ??? ??? ?System.out.println();
?? ??? ?}
?? ?}
}
?
總結
以上是生活随笔為你收集整理的Leetcode--78. 子集的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leetcode--151. 翻转字符串
- 下一篇: 计算机丢失first,求大神解答硬盘驱动