题解 | #全排列#

全排列

https://www.nowcoder.com/practice/5632c23d0d654aecbc9315d1720421c1

//C++版代码
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
    string s;
    cin >> s;
    do {
        cout << s << endl;
    } while (next_permutation(s.begin(), s.end()));
    return 0;
}
//Java版代码
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
    private static List<String> result = new ArrayList<>();
    private static StringBuilder path = new StringBuilder();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.next();
        backtracking(s);
        result.forEach(System.out::println);
    }
    private static void backtracking(String s) {
        if (path.length() == s.length()) {
            result.add(new String(path));
            return;
        }
        for (int i = 0; i < s.length(); i++) {
            if (path.indexOf(String.valueOf(s.charAt(i))) != -1) continue;
            path.append(s.charAt(i));
            backtracking(s);
            path.deleteCharAt(path.length() - 1);
        }
    }
}
//Python版代码
from itertools import permutations
print(*map(''.join, permutations(input())), sep='\n')

全部评论

相关推荐

10-11 17:45
门头沟学院 Java
走吗:别怕 我以前也是这么认为 虽然一面就挂 但是颇有收获!
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务