image.png
    尝试模型:
    从左到右,只不过index表示第几个位置的字符。N叉树问题

    image.png
    从剩余的字符中选择一个没有出现过的字符

    1. * 排列组合问题
    2. */
    3. public class T27_Per_Com {
    4. public static void main(String[] args) {
    5. String str = "abc";
    6. process(str.toCharArray(), 0, "");
    7. }
    8. public static void process(char[] chs, int index, String str){
    9. if(index == chs.length) {
    10. System.out.println(str + " ===");
    11. return;
    12. }
    13. for(int i = 0 ; i < chs.length ; i++){
    14. if(chs[i] != 0 ){
    15. char temp = chs[i];
    16. chs[i] = 0;
    17. process(chs, index +1, str+ String.valueOf(temp));
    18. chs[i] = temp;
    19. }
    20. }
    21. }
    22. }

    解法2: 任意两个字符交换,
    通过交换的方式,避免上面for循环的多余遍历。
    str承载了之前做的选择
    image.png
    image.png
    组合就是去掉注释后的代码
    意思是aabb这样的组合,有重复的,要去重,那就看该位置有没有做过此元素的遍历。
    就是避免交换的字符已经试过了。
    tips: 可以先permutation,然后再去重,常数复杂度高
    加上注释,提前杀死不可能走的路径,分支定界。