Day 22 回溯法part04| LeetCode 491.递增子序列,46.全排列,47.全排列 II

491.递增子序列

491. 非递减子序列

    class Solution {
        public  List<Integer> path=new LinkedList<>();
        public  List<List<Integer>> res=new ArrayList<>();
        public List<List<Integer>> findSubsequences(int[] nums) {

            backtraking(nums,0);

            return res;

        }
        void backtraking(int[] nums,int startIndex)
        {
            if(path.size()>=2)

            {
                res.add(new ArrayList<>(path));
            }
        
            HashSet<Integer> hs=new HashSet<>();
            for(int i=startIndex;i<nums.length;i++)
            {
                //去重,树层不能重复
                if(!path.isEmpty()&&path.get(path.size()-1)>nums[i]|| hs.contains(nums[i])) continue;

                hs.add(nums[i]);
                path.add(nums[i]);

                backtraking(nums,i+1);

                path.remove(path.size()-1);

            }

        }
    }

46.全排列

46. 全排列

class Solution {
        public  List<Integer> path=new LinkedList<>();
        public  List<List<Integer>> res=new ArrayList<>();

        public List<List<Integer>> permute(int[] nums) {

            int[] used=new int[nums.length];
            backtraking(nums,used);
            return res;
        }

        void backtraking(int[] nums,int[] used)
        {

            if (path.size()==nums.length)
            {
                res.add(new ArrayList<>(path));
                return;
            }
          for(int i=0;i< nums.length;i++)
          {
              if(used[i]==0)
              {
                  path.add(nums[i]);
                  used[i]=1;
                  backtraking(nums,used);
                  path.remove(path.size()-1);
                  used[i]=0;
              }

          }
        }
    }

47.全排列 II

47. 全排列 II

  class Solution {
        public  List<Integer> path=new LinkedList<>();
        public  List<List<Integer>> res=new ArrayList<>();

        public List<List<Integer>> permuteUnique(int[] nums) {

            Arrays.sort(nums);
            int[] used=new int[nums.length];
            backtraking(nums,used);
            return res;
        }

        void backtraking(int[] nums,int[] used)
        {

            if (path.size()==nums.length)
            {
                res.add(new ArrayList<>(path));
                return;
            }
          for(int i=0;i< nums.length;i++)
          {
             if(i>0&&nums[i]==nums[i-1]&&used[i-1]==0)continue;
              if(used[i]==0)
              {
                  path.add(nums[i]);
                  used[i]=1;
                  backtraking(nums,used);
                  path.remove(path.size()-1);
                  used[i]=0;
              }

          }
        }
  }

332.重新安排行程 (一刷跳过)

51.N皇后(一刷跳过)

37.解数独(一刷跳过)

posted on 2024-09-22 20:19  FreeDrama  阅读(2)  评论(0编辑  收藏  举报

导航