题解 | #字符串的排列#

字符串的排列

https://www.nowcoder.com/practice/fe6b651b66ae47d7acce78ffdd9a96c7

import java.util.ArrayList;
public class Solution {
    public ArrayList<String> Permutation(String str) {
   ArrayList<String> ret = new ArrayList<String>();
   char[] chs=str.toCharArray();
        dfs(chs, ret, 0);
        return ret;
    }

        public void dfs(char[] nums, ArrayList<String> ret, int k) {
        if (k == nums.length) {
            String str="";
            for (int i = 0; i < nums.length; i++) {
                str+=nums[i];
            }
            ret.add(str);
            return;
        }
        ArrayList<Character> tempList=new ArrayList<>();
        for (int i = k; i < nums.length; i++) {
             if(i!=k&&nums[i]==nums[k]||tempList.contains(nums[i])){
                continue;
            }
            swap(nums, k, i);
            dfs(nums, ret, k + 1);
            swap(nums, k, i);
            tempList.add(nums[i]);
        }
    }

    public void swap(char[] nums, int i, int j) {
        char temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务