121.文字列の配置

タイトル説明

文字列を入力し、文字列内のすべての文字を辞書式順序で出力します。たとえば、文字列abcを入力し、文字a、b、cで辞書式順序に並べることができるすべての文字列abc、acb、bac、bca、cab、およびcbaを出力します。

説明を入力してください:

文字列を入力します。長さは9を超えません(文字が繰り返される場合があります)。文字には大文字と小文字のみが含まれます。

例1

入る

"ab"

戻り値

["ab","ba"]

コードの実装

import java.util.*;
public class Solution {
    public ArrayList<String> Permutation(String str) {
       Set<String> res = new HashSet<>();
        if (str == null || str.length() == 0) {
            return new ArrayList<String>();
        }
        helper(res, 0, str.toCharArray());
        ArrayList<String> result = new ArrayList(res);
        Collections.sort(result);
        return result;
    }
    
    public void helper(Set<String> res, int index, char[] arr) {
        if (index == arr.length - 1) {
            res.add(new String(arr));
            return;
        }
        for (int i = index; i < arr.length; i++) {
            swap(arr, index, i);
            helper(res, index + 1, arr);
            swap(arr, index, i);
        }
    }
    
    public void swap(char[] arr, int i, int j){
            char tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
    }
}

 

おすすめ

転載: blog.csdn.net/xiao__jia__jia/article/details/113484893