题目:有 1、2、3、4 个数字,能组成多少个互不相同且无重复数字的三位数?都是多少?
1.程序分析:可填在百位、十位、个位的数字都是 1、2、3、4。组成所有的排列后再去
掉不满足条件的排列:
Go语言程序源代码:
package main import ( "fmt" ) func main() { /*以下为三重循环*/ for i := 1; i < 5; i++ { for j := 1; j < 5; j++ { for k := 1; k < 5; k++ { /*确保 i 、j 、k 三位互不相同*/ if i != k && i != j && j != k { fmt.Println(i, j, k) } } } } }
C语言程序源代码:
#include <stdio.h> #include <stdlib.h> #define N 4 void perm(int*, int, void (*)(int*)); void rotate(int*, int, int); void copy(int*, int*); void print(int*); int main(void) { int num[N] = {1, 2, 3, 4}; perm(num, 0, print); return 0; } void perm(int* num, int i, void (*take)(int*)) { if(i < N) { int j; for(j = i; j < N; j++) { int to[N]; copy(num, to); rotate(to, i, j); perm(to, i + 1, take); } } else { take(num); } } void rotate(int* num, int i, int j) { int tmp = num[j]; int k; for(k = j; k > i; k--) { num[k] = num[k - 1]; } num[i] = tmp; } void copy(int* from, int* to) { int i; for(i = 0; i < N; i++) { to[i] = from[i]; } } void print(int* num) { int i; for(i = 0; i < N; i++) { printf("%d ", num[i]); } printf("//n"); }
Java语言程序源代码:
import java.util.*; public class Permutation { public static <T> List<T> rotatedTo(int i, List<T> list) { List<T> rotated = new ArrayList<>(); rotated.add(list.get(i)); rotated.addAll(list.subList(0, i)); rotated.addAll(list.subList(i + 1, list.size())); return rotated; } public static <T> List<List<T>> allRotated(List<T> list) { List<List<T>> allRotated = new ArrayList<>(); for(int i = 0; i < list.size(); i++) { allRotated.add(rotatedTo(i, list)); } return allRotated; } public static <T> List<List<T>> perm(List<T> list) { List<List<T>> pls = new ArrayList<>(); if(list.isEmpty()) { pls.add(new ArrayList<T>()); } else { for(List<T> lt : allRotated(list)) { for(List<T> tailPl : perm(lt.subList(1, lt.size()))) { List<T> pl = new ArrayList<>(); pl.add(lt.get(0)); pl.addAll(tailPl); pls.add(pl); } } } return pls; } public static void main(String[] args) { for(List<Integer> pl : perm(Arrays.asList(1, 2, 3, 4))) { System.out.println(pl); } } }
JavaScript语言程序源代码:
function allRotated(list) { function rotatedTo(i) { var rotated = []; rotated.push(list[i]); return rotated.concat(list.slice(0, i)) .concat(list.slice(i + 1, list.length)); } var all = []; for(var i = 0; i < list.length; i++) { all.push(rotatedTo(i)); } return all; } function perm(list) { var pls = []; if(list.length == 0) { pls.push([]); } else { allRotated(list).forEach(function(lt) { perm(lt.slice(1, lt.length)).forEach(function(tailPl) { var pl = []; pl.push(lt[0]); pls.push(pl.concat(tailPl)); }); }); } return pls; } perm([1, 2, 3, 4]).forEach(function(lt) { print(lt); });
经典算法-数字排列组合