DFS-all non-repeating permutations of the string aab (aab, aba, baa)

topic:

exsample1:

Input "abc"
to output [ [a,b,c], [a,c,b], [b,a,c], [b,c,a], [c,a,b], [c,b ,a] ], the result needs to be deduplicated, that is, all permutations of "abc" are given (permutations also belong to DFS)

example2:

Input "aab"
output: under normal circumstances: [[aab], [aba], [aab], [aba], [baa], [baa]], if you want the result elements not to be repeated, you need to deduplicate the result as
[ [aab], [aba], [baa]]

Graphical reference article:

https://blog.csdn.net/Strom72/article/details/80738818, I will not draw

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
 * Author:m
 * Date: 2023/04/14 22:07
 */
public class PermutationNotRepeat {
    
    
    public static void main(String[] args) {
    
    
        String s = "aab";
        List<List<String>> res = dfs(s);
        // 正常情况下:[[aab], [aba], [aab], [aba], [baa], [baa]],想要结果元素不重复,则需要去重
        // [[aab], [aba], [baa]]
        System.out.println(res);
    }

    private static List<List<String>> dfs(String s) {
    
    
        if (StringUtils.isBlank(s)) {
    
    
            return Lists.newArrayList();
        }

        List<List<String>> result = Lists.newArrayList();
        permutation(result, s.toCharArray(), 0);
        return result;
    }

    private static void permutation(List<List<String>> result, char[] chars, int i) {
    
    
        // 1.终止条件
        // 2.大容器添加小容器
        if (i == chars.length) {
    
    
            result.add(Lists.newArrayList(String.valueOf(chars)));
        }
        // 3.循环
        Set<Character> set = new HashSet<>();
        for (int j = i; j < chars.length; j++) {
    
    
            // 3.1过滤|去重
            if (set.contains(chars[j])) {
    
    
                continue;
            }
            // 3.2优化减支
            // 3.3小容器添加元素(这里使用chars数组本身作为我们的小容器)
            set.add(chars[j]);
            swap(chars, i, j);
            // 3.4递归(横向是bfs,即循环即j++、纵向是dfs,即递归即i++)
            permutation(result, chars, i + 1);
            // 3.5回溯(原本是删除小容器的最后一个元素,这里是将小容器即chars数组还原,因为我们使用它作为小容器进行变化然后添加至大容器,所以作为数组本身还需要回溯回来)
            swap(chars, i, j);
        }
    }

    private static void swap(char[] chars, int i, int j) {
    
    
        char temp = chars[i];
        chars[i] = chars[j];
        chars[j] = temp;
    }
}

Guess you like

Origin blog.csdn.net/tmax52HZ/article/details/130163589