oj 1015 遞歸

題意:輸入一個字符串s,一個目標值target,求出V,W,X,Y,Z(v,w,x,y,z屬於s)使得x-w^2+x^3-y^4+z^5=target(v,w,x,y用字母表中的順序代替)成立,若有多個成立,輸出最大的VWXYZ.

由於要輸出最大的VWXYZ,所以要先對s排序。再使用遞歸。

visited[i]表示s[i]是否已被訪問過。

 

import java.util.Scanner;

import static java.util.Arrays.sort;

public class Main_1015 {
    static  int[] des;
    static int[] result;
    static  boolean[] visited;
    static boolean success;
    public static void main(String[] args)  {
        Scanner in = new Scanner(System.in);
        while(true){
            int target = in.nextInt();
            String  source = in.next();
            if(target == 0 && source.equals("END")){
                break;
            }
            int len = source.length();
            des = new int[len];
            result = new int[5];
            success = false;
            visited = new boolean[len];

            init(source);
            sort(des);
            dfs(0,target);
            if(success){
                for(int i = 0;i < 5; i++){
                    System.out.print((char)(result[i]+'A'-1));
                }
                System.out.println();
            }else{
                System.out.println("no solution");
            }

        }

    }
    public static void dfs(int depth,int target){
        if(success){
            return;
        }
        if(depth == 5){
            check(target);
            return;
        }
        for(int i = des.length-1; i >=0; i--){
            if(!visited[i] && !success){
                result[depth] = des[i];
                visited[i] = true;
                dfs(depth+1,target);
                visited[i]= false;
            }
        }
    }
    public static int[] init(String source){
        for(int i = 0; i < source.length(); i++){
            des[i] = source.charAt(i) -'A' +1;
        }
        return des;
    }
    public static void check(int target){
        if(target==result[0] - result[1] * result[1] + result[2]*result[2]*result[2] - Math.pow(result[3],4) + Math.pow(result[4],5)){
            success = true;
            return;
        }
        return;
    }
}

 

注意:遞歸的結果可以用全局變量記錄,這樣當滿足條件時,可以使得棧中其他的上層函數直接返回。

參考:https://blog.csdn.net/pengwill97/article/details/54882698

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章